Created
May 4, 2016 18:33
-
-
Save nitinbhojwani/a5f9bab74185b04ad6e73e37a970ad37 to your computer and use it in GitHub Desktop.
Django - Send a Mail with Attachment File like CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import EmailMessage class - https://docs.djangoproject.com/en/1.9/topics/email/#django.core.mail.EmailMessage | |
from django.core.mail import EmailMessage | |
email = EmailMessage('... Subject ...', '... Body ...', 'from-email', | |
['to-email-1', 'to-email-2'], ['bcc-email-1', 'bcc-email-2']) | |
# now let's create a csv file dynamically | |
import csv, StringIO | |
attachment_csv_file = StringIO.StringIO() | |
writer = csv.writer(attachment_csv_file) | |
labels = ['name', 'city', 'email'] | |
writer.writerow(labels) | |
rows = [['Nitin', 'Bengaluru', '[email protected]'], ['X', 'Y', 'Z']] | |
for row in rows: | |
writer.writerow(row) | |
email.attach('attachment_file_name.csv', attachment_csv_file.getvalue(), 'text/csv') | |
email.send(fail_silently=False) |
Cool. I will try that. Thanks!!
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Ankit-Kr-Singh I found that fallowing works:
Changing this line:
email.attach('attachment_file_name.csv', attachment_csv_file.getvalue(), 'text/csv')
To this:
email.attach('attachment_file_name.csv', attachment_csv_file.getvalue().encode(), 'application/octet-stream')
As an additional workout, until the django sendgrid package will be fixed.