说明: 我们常常会用到一些发送邮件的功能,尽管Python
已经提供了相对易用的邮件发送模块smtplib
。但Django
仍对其做了轻度的封装。封装后的模块EmailMultiAlternatives
不仅发送邮件速度快,而且在开发环境下也很容易对邮件发送进行测试。下面我们看一下如何实现。
步骤:
- 去对应的邮箱网站获取邮箱授权码
在Django项目的
settings.py
中设置EMAIL_HOST = "smtp.qq.com" EMAIL_PORT = 465 # ssl协议端口号 EMAIL_HOST_USER = "742323587@qq.com" EMAIL_HOST_PASSWORD = "授权密码" EMAIL_USE_SSL = True # 是否使用安全套接字层,一般都是True EMAIL_FROM = EMAIL_HOST_USER
在
views.py
里编写视图from smtplib import SMTPRecipientsRefused from django.core.mail import EmailMultiAlternatives msg = EmailMultiAlternatives(subject, html_content, EMAIL_FROM, [to_email]) msg.attach_alternative(html_content, "text/html") try: msg.send() except SMTPRecipientsRefused as e: print(str(e))
如果你不想把邮箱设置写死在
settings.py
中,你还可以这样写:from smtplib import SMTPRecipientsRefused from django.core.mail import EmailMultiAlternatives, get_connection msg_list = [] msg = EmailMultiAlternatives(subject, html_content, EMAIL_FROM, [to_email]) msg.attach_alternative(html_content, "text/html") msg_list.append(msg) conn = get_connection() conn.username = EMAIL_HOST_USER conn.password = EMAIL_HOST_PASSWORD conn.port = EMAIL_PORT conn.host = EMAIL_HOST conn.use_ssl = EMAIL_USE_SSL try: conn.send_messages(msg_list) except SMTPRecipientsRefused as e: print(str(e)) conn.close()
总结: 如果不报错就表示发送成功了,可以打开邮箱看一下!
你的文章充满了创意,真是让人惊喜。 http://www.55baobei.com/eXXfSeEXvF.html