Django发送Html邮件

Django发送文字邮件

message = "".join([
    u"【{}】您本次操作的验证码如下:{}\n\n".format(email_verify.get_purpose_display(),
                                     email_verify.code),
    u"如果这不是您本人的操作,请忽略本邮件!\n",
    u"DreamGo官网:http://{}\n\n".format('www.dreamgo.tech'),
    "谢谢!\n",
    "南京诗远启账户团队\n",
])
from_email = 'verify@dreamgo.tech'
try:
    send_mail('DreamGo账户邮箱认证', message, from_email, [tel_email])
    return success_response('邮件已发送')
except Exception as e:
    return error_response(5, '邮件发送失败 原因:' + str(e))

Django发送Html邮件

方法1:

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

message = get_template('page.html').render({
    'bg_url': bg_url,
})
msg = EmailMessage(subject, message, to=[to], from_email=from_email)
msg.content_subtype = 'html'
msg.send()

方法2:

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

subject, from_email, to = get_value(settings.SITE_NAME), 'DreamGoTech@dreamgo.tech', '614457662@qq.com'

msg_html = render_to_string('page.html', context={
    'bg_url': bg_url,
}, request=request)

msg = EmailMultiAlternatives(subject, '', 'Dreamgo<verify@dreamgo.tech>', [to])
msg.attach_alternative(msg_html, "text/html")
msg.send()

使用方法2发送带静态文件的Html

bg_url = request.build_absolute_uri('/static/images/email_verify_head.jpg')
user_name = request.user.get_full_name() if request.user.is_authenticated else ''
msg_html = render_to_string('email/verify.html', context={
    'bg_url': bg_url,
    'user_name': user_name,
    'verify_purpose': email_verify.get_purpose_display(),
    'verify_code': email_verify.code,
    'verify_duration': email_verify.duration,
    'current_time': datetime.now().date()
}, request=request)
subject = '{} {}'.format(get_value(settings.SITE_NAME), email_verify.get_purpose_display())
msg = EmailMultiAlternatives(subject, '', settings.DEFAULT_FROM_EMAIL, [tel_email])
msg.attach_alternative(msg_html, "text/html")

try:
    msg.send()
    return success_response('邮件已发送')
except Exception as e:
    return error_response(5, '邮件发送失败 原因:' + str(e))

静态文件使用request.build_absolute_uri方法获取绝对路径,在html中使用格式为

<div class="header">
    <img src="{{ bg_url }}" />
</div>

Email中html语法的特殊要求

Html在发送邮件时,Gmail不支持标签中的background实现,会导致图片无法加载。具体支持语法情况可至此处查看。

一般来说,email中的html有如下几点要求:

不可以:

  • Include a section with styles. Apple Mail.app supports it, but Gmail and Hotmail do not, so it's a no-no. Hotmail will support a style section in the body but Gmail still doesn't.
  • Link to an external stylesheet. Not many email clients support this, best to just forget it.
  • Background-image / Background-position. Gmail is also the culprit on this one.
  • Clear your floats. Gmail again.
  • Margin. Yep, seriously, Hotmail ignores margins. Basically any CSS positioning at all doesn't work.
  • Font-anything. Chances are Eudora will ignore anything you try to declare with fonts.

只可以使用inline styles来完成Html样式实现.

https://css-tricks.com/using-css-in-html-emails-the-real-story/

发件邮箱设置别名显示:

设置send_email方法的from_user为

'DreamGo<verify@dreamgo.tech>'

<>里必须为自己的发件邮箱地址,前面为真正显示在客户端的邮箱别名。

邮件