Marcolac
Marcolac

Reputation: 931

Send a .txt with send_mail. Django

I want to send an email with django and I want the body of email to contains content from .txt file. I import from my templates. I went through the docs but I didn't find how to do it.

Here is what I have in my views.py:

 send_mail('TEST', 'myfile.txt', '[email protected]', [[email protected]], fail_silently=False)

I tried to add myfile.txt to my template directory. But when I replace 'myfile.txt' by myfile.txt in send_mail(), I off course got an error because myfile.txt is not a defined variable. Any idea on how I can accomplish that?

Upvotes: 3

Views: 1873

Answers (2)

trinchet
trinchet

Reputation: 6933

What you need is render_to_string,

from django.template.loader import render_to_string
body = render_to_string('myfile.txt', foovars)
send_mail('TEST', body, '[email protected]', [[email protected]], fail_silently=False)

where foovars is a dict with the values that you need to render in the 'template' myfile.txt if proceed of course, else {}

be sure your myfile.txt lies on your template directory, that is all ;-)

Upvotes: 4

Aamir Rind
Aamir Rind

Reputation: 39709

If you want body of your email message to be the content of myfile.txt then (suppose myfile.txt is stored in media > files > myfile.txt):

from mysite.settings import MEDIA_ROOT
import os

file = open(MEDIA_ROOT + os.path.sep + 'files/myfile.txt', 'r')
content = file.read()
file.close()

# EmailMessage class version
mail = EmailMessage('subject', content, '[email protected]', ['[email protected]'])
mail.send()

# send_mail version
send_mail('TEST', content, '[email protected]', [[email protected]], fail_silently=False)

Upvotes: 2

Related Questions