Sending email with attached .ods File

319 views Asked by At
send_mail('Subject here', 'Here is the message.', '[email protected]', ['[email protected]'], fail_silently=False)
mail = send_mail('Subject here', 'Here is the message.', '[email protected]', ['[email protected]'], fail_silently=False)
mail.attach('AP_MODULE_bugs.ods','AP_MODULE_bugs.ods','application/vnd.oasis.opendocument.spreadsheet')
mail.send()

I'm using Django send_mail class for sending mail. Here I want to send mail with attachment, my attachment File (.ods) is in local storage.

2

There are 2 answers

1
Tevin Joseph K O On BEST ANSWER

You have to use EmailMessage

from django.core.mail import EmailMessage

email = EmailMessage(
    'Hello',
    'Body goes here',
    '[email protected]',
    ['[email protected]', '[email protected]'],
    ['[email protected]'],
    reply_to=['[email protected]'],
    headers={'Message-ID': 'foo'},

)

mail.attach('AP_MODULE_bugs.ods',mimetype='application/vnd.oasis.opendocument.spreadsheet')

mail.send()

attach() creates a new file attachment and adds it to the message. There are two ways to call attach():

  • You can pass it a single argument that is an email.MIMEBase.MIMEBase instance. This will be inserted directly into the resulting message.
  • Alternatively, you can pass attach() three arguments: filename, content and mimetype. filename is the name of the file attachment as it will appear in the email, content is the data that will be contained inside the attachment and mimetype is the optional MIME type for the attachment. If you omit mimetype, the MIME content type will be guessed from the filename of the attachment.

    Eg: message.attach('design.png', img_data, 'image/png')

2
Rakesh On

try using attach_file()

Ex:

mail = EmailMessage('Subject here', 'Here is the message.', '[email protected]',  ['[email protected]'])
mail.attach_file('PATH TO AP_MODULE_bugs.ods', mimetype='application/vnd.oasis.opendocument.spreadsheet')
mail.send()