Send Excel Attachment by Email Using Django

Here is a snippet for sending an attachment by email in Django:

import base64
import os

from django.core.mail import EmailMessage


def send_mail_w_attachment(to, subject, message, attachment_path,
                           mimetype='application/octet-stream', fail_silently=False):
    """
    :param to: a list of email addresses
    :param subject: a string
    :param message: a string
    :param attachment_path: full path to attachment fil
    """
    email = EmailMessage(subject, message, to=to)

    # Load file and Base64 encode
    file_name = os.path.basename(attachment_path)
    data = open(attachment_path, 'rb').read()
    encoded = base64.b64encode(data)
    email.attach(file_name, encoded, mimetype=mimetype)

    # Send it
    email.send(fail_silently=fail_silently)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s