说明: 我们常常会用到一些发送邮件的功能,尽管Python已经提供了相对易用的邮件发送模块smtplib。但Django仍对其做了轻度的封装。封装后的模块EmailMultiAlternatives不仅发送邮件速度快,而且在开发环境下也很容易对邮件发送进行测试。下面我们看一下如何实现。

步骤:

  1. 去对应的邮箱网站获取邮箱授权码
  2. 在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
  3. 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()

总结: 如果不报错就表示发送成功了,可以打开邮箱看一下!

Last modification:April 19th, 2020 at 11:43 am