Search code examples
pythondjangodjango-rest-frameworkdjango-mailer

Sending email with attached .ods File


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.


Solution

  • 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')