Skip to content

Instantly share code, notes, and snippets.

@nitinbhojwani
Created May 4, 2016 18:33
Show Gist options
  • Save nitinbhojwani/a5f9bab74185b04ad6e73e37a970ad37 to your computer and use it in GitHub Desktop.
Save nitinbhojwani/a5f9bab74185b04ad6e73e37a970ad37 to your computer and use it in GitHub Desktop.
Django - Send a Mail with Attachment File like CSV
# 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', 'nitinbhojwani1993@gmail.com'], ['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)
@Ankit-Kr-Singh
Copy link

Cool. I will try that. Thanks!!

@siddharth-cm
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment