我想发送html电子邮件,使用Django模板,像这样:

<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>

我找不到任何关于send_mail的东西,django-mailer只发送HTML模板,没有动态数据。

如何使用Django的模板引擎生成电子邮件?


当前回答

我写了一个代码片段,允许您发送使用存储在数据库中的模板渲染的电子邮件。一个例子:

EmailTemplate.send('expense_notification_to_admin', {
    # context object that email template will be rendered with
    'expense': expense_request,
})

其他回答

我知道这是一个老问题,但我也知道有些人就像我一样,总是在寻找最新的答案,因为旧的答案如果不更新有时会有过时的信息。

现在是2020年1月,我使用的是Django 2.2.6和Python 3.7

注意:我使用DJANGO REST框架,下面发送电子邮件的代码是在我的views.py的模型视图集中

所以在看了很多不错的答案之后,我就这么做了。

from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives

def send_receipt_to_email(self, request):

    emailSubject = "Subject"
    emailOfSender = "email@domain.com"
    emailOfRecipient = 'xyz@domain.com'

    context = ({"name": "Gilbert"}) #Note I used a normal tuple instead of  Context({"username": "Gilbert"}) because Context is deprecated. When I used Context, I got an error > TypeError: context must be a dict rather than Context

    text_content = render_to_string('receipt_email.txt', context, request=request)
    html_content = render_to_string('receipt_email.html', context, request=request)

    try:
        #I used EmailMultiAlternatives because I wanted to send both text and html
        emailMessage = EmailMultiAlternatives(subject=emailSubject, body=text_content, from_email=emailOfSender, to=[emailOfRecipient,], reply_to=[emailOfSender,])
        emailMessage.attach_alternative(html_content, "text/html")
        emailMessage.send(fail_silently=False)

    except SMTPException as e:
        print('There was an error sending an email: ', e) 
        error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'}
        raise serializers.ValidationError(error)

重要!那么render_to_string如何获得receipt_email.txt和receipt_email.html? 在我的settings.py中,我有TEMPLATES,下面是它的外观

注意DIRS,这里有一行os。path。join(BASE_DIR, 'templates', 'email_templates') 这一行使我的模板可访问。在我的project_dir中,我有一个文件夹叫做templates,还有一个子目录叫做email_templates,就像这个project_dir->templates->email_templates。我的模板receipt_email.txt和receipt_email.html在email_templates子目录下。

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'email_templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

我再加上,我的receit_email。txt是这样的;

Dear {{name}},
Here is the text version of the email from template

我的receipt_email。html是这样的;

Dear {{name}},
<h1>Now here is the html version of the email from the template</h1>

我写了一个代码片段,允许您发送使用存储在数据库中的模板渲染的电子邮件。一个例子:

EmailTemplate.send('expense_notification_to_admin', {
    # context object that email template will be rendered with
    'expense': expense_request,
})

Django Mail Templated是一个功能丰富的Django应用程序,可以用Django模板系统发送电子邮件。

安装:

pip install django-mail-templated

配置:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

模板:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

更多信息:https://github.com/artemrizhov/django-mail-templated

我创建了Django Simple Mail,为你想发送的每一封事务性电子邮件提供了一个简单的、可定制的和可重用的模板。

邮件内容和模板可以直接从django的管理编辑。

在你的例子中,你会注册你的电子邮件:

from simple_mail.mailer import BaseSimpleMail, simple_mailer


class WelcomeMail(BaseSimpleMail):
    email_key = 'welcome'

    def set_context(self, user_id, welcome_link):
        user = User.objects.get(id=user_id)
        return {
            'user': user,
            'welcome_link': welcome_link
        }


simple_mailer.register(WelcomeMail)

然后用这种方式发送:

welcome_mail = WelcomeMail()
welcome_mail.set_context(user_id, welcome_link)
welcome_mail.send(to, from_email=None, bcc=[], connection=None, attachments=[],
                   headers={}, cc=[], reply_to=[], fail_silently=False)

我很乐意得到任何反馈。

如果您想要为您的邮件设置动态电子邮件模板,请将电子邮件内容保存在数据库表中。 这是我保存为HTML代码在database =

<p>Hello.. {{ first_name }} {{ last_name }}.  <br> This is an <strong>important</strong> {{ message }}
<br> <b> By Admin.</b>

 <p style='color:red'> Good Day </p>

在你看来:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template

def dynamic_email(request):
    application_obj = AppDetails.objects.get(id=1)
    subject = 'First Interview Call'
    email = request.user.email
    to_email = application_obj.email
    message = application_obj.message

    text_content = 'This is an important message.'
    d = {'first_name': application_obj.first_name,'message':message}
    htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code

    open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
    text_file = open("partner/templates/first_interview.html", "w") # opening my file
    text_file.write(htmly) #putting HTML content in file which i saved in DB
    text_file.close() #file close

    htmly = get_template('first_interview.html')
    html_content = htmly.render(d)  
    msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

这将发送您保存在Db中的动态HTML模板。