3

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', 'admin@test.com', [test@test.com], 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?

4

2 に答える 2

3

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, 'admin@test.com', [test@test.com], 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 ;-)

于 2012-12-23T18:09:29.800 に答える
2

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, 'from@example.com', ['to@example.com'])
mail.send()

# send_mail version
send_mail('TEST', content, 'admin@test.com', [test@test.com], fail_silently=False)
于 2012-12-23T13:57:28.153 に答える