如何在Django中使用send_mail自定义邮件发送内容
Django 向Gmail发送自定义富文本邮件实现指南
一、基础配置(Gmail专属配置)
首先在项目settings.py中配置邮件服务参数,注意Gmail现在已不支持直接用账号密码登录,需要先在Google账号中开启两步验证,再生成应用专用密码使用:
# settings.py 配置项 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '你的Gmail邮箱地址' EMAIL_HOST_PASSWORD = '你生成的Gmail应用专用密码' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
二、富文本邮件发送核心实现
Django支持两种发送富文本HTML邮件的方式,推荐使用EmailMultiAlternatives实现,兼容性更强:
方式1:使用send_mail快速实现
直接传入html_message参数即可发送HTML内容:
from django.core.mail import send_mail def send_custom_mail(receiver_email): subject = '邮件标题' plain_message = '如果收件箱不支持HTML显示时展示的纯文本内容' html_message = """ <div> <h2>Hello World</h2> <p>这是富文本邮件内容</p> </div> """ send_mail( subject=subject, message=plain_message, from_email=None, # 用settings里的默认发件人 recipient_list=[receiver_email], html_message=html_message )
方式2:使用EmailMultiAlternatives(推荐)
支持更复杂的附件、内嵌图片等需求:
from django.core.mail import EmailMultiAlternatives def send_rich_mail(receiver_email): subject = '富文本测试邮件' text_content = '您的邮箱不支持HTML显示时会看到这段内容' # 这里可以写完整的HTML富文本代码,包含布局、按钮、图片等 html_content = """ <table width="100%" cellpadding="0" cellspacing="0" style="max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif;"> <tr> <td style="padding: 20px; background-color: #f5f5f5;"> <h1 style="color: #333; text-align: center;">欢迎使用我们的服务</h1> </td> </tr> <tr> <td style="padding: 30px 20px;"> <p style="font-size: 16px; color: #666; line-height: 1.5;">您好,这是您的专属验证邮件:</p> <!-- 按钮实现,用table兼容所有邮箱 --> <table cellpadding="0" cellspacing="0" style="margin: 20px auto;"> <tr> <td style="border-radius: 4px; background-color: #4285f4;"> <a href="你的业务跳转链接" style="display: inline-block; padding: 12px 24px; color: #fff; text-decoration: none; font-size: 16px; font-weight: bold;">点击验证</a> </td> </tr> </table> <!-- 图片示例,用公网可访问直链或者CID内嵌 --> <p style="text-align: center; margin-top: 30px;"> <img src="你的图片公网访问地址" alt="宣传图" style="max-width: 100%; height: auto;"> </p> </td> </tr> <tr> <td style="padding: 15px 20px; background-color: #eee; text-align: center; font-size: 14px; color: #999;"> 系统邮件,请勿直接回复 </td> </tr> </table> """ msg = EmailMultiAlternatives(subject, text_content, to=[receiver_email]) msg.attach_alternative(html_content, "text/html") # 如果需要添加附件可以用msg.attach_file()方法 msg.send()
三、Gmail富文本兼容注意事项
Gmail对HTML邮件的支持有较多限制,需要遵守以下规则保证渲染正常:
- 所有样式必须写行内style属性,不要写外部CSS文件、不要写style标签内的样式,Gmail会过滤掉
- 页面布局全部用
table标签实现,不要用div+css的flex、grid等现代布局方式,避免排版错乱 - 按钮不要用原生
button标签,用table嵌套a标签的方式实现,如上面示例中的代码 - 图片不要用本地路径,要么用公网可直接访问的HTTP/HTTPS直链,要么使用CID内嵌到邮件中
- 不要使用JavaScript、iframe等内容,Gmail会直接过滤
- 邮件整体宽度建议控制在600px以内,适配移动端展示
内容的提问来源于stack exchange,提问作者Avatar
相关产品推荐
相关产品推荐

