[Django]-Send email with attachment django

3👍

Assuming you have a model as,

class MyModel(models.Model):
    # other fields
    presentation = models.FileField(upload_to='some/place/')

and in your signals,

import mimetypes


def mail_business_plan(sender, instance, created, **kwargs):
    if created:
        ctx = {"ctx": instance}

        from_email = 'info@some_email.in'

        subject = 'Business Plan by' + instance.company_name
        message = get_template('email/business_team.html').render(ctx)
        to = ['some_email@gmail.com']
        mail = EmailMessage(subject, message, to=to, from_email=from_email)

        content_type = mimetypes.guess_type(instance.presentation.name)[0] # change is here <<<
        mail.attach_file(instance.presentation, instance.presentation.read(), content_type) # <<< change is here also

        return mail.send()

Reference:
mimetypes.guess_type()

👤JPG

0👍

Best way to send email in python is using smtp

Here are the steps to configure postfix in ubuntu and send mail.

  1. sudo apt-get install mailutils

    just press ok for all the popup (you can change the hostname later)

  2. sudo vim /etc/postfix/main.cf

    change the following line from inet_interfaces = all to inet_interfaces = localhost

  3. sudo service postfix restart

Try the following code after you done with all these steps

import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_email(subject, message, from_email, to_email=[], attachment=[]):
    """
    :param subject: email subject
    :param message: Body content of the email (string), can be HTML/CSS or plain text
    :param from_email: Email address from where the email is sent
    :param to_email: List of email recipients, example: ["a@a.com", "b@b.com"]
    :param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ", ".join(to_email)
    msg.attach(MIMEText(message, 'html'))

    for f in attachment:
        with open(f, 'rb') as a_file:
            basename = os.path.basename(f)
            part = MIMEApplication(a_file.read(), Name=basename)

        part[
            'Content-Disposition'] = 'attachment; filename="%s"' % basename
        msg.attach(part)

    email = smtplib.SMTP('localhost')
    email.sendmail(from_email, to_email, msg.as_string())

0👍

I got the solution by changing

mail.attach_file(instance.presentation, instance.presentation.read(), instance.presentation.content_type)

to

mail.attach_file(instance.presentation.path)
👤daemon

Leave a comment