SMTP 之 Python3.6 及以上调用示例

使用 Python3.6及以上通过 SMTP 协议发信

  1. # -*- coding:utf-8 -*-
  2. import smtplib
  3. import email
  4. # import json
  5. # import base64
  6. from email.mime.multipart import MIMEMultipart
  7. from email.mime.text import MIMEText
  8. # from email.mime.image import MIMEImage
  9. # from email.mime.base import MIMEBase
  10. # from email.mime.application import MIMEApplication
  11. from email.header import Header
  12. from email.utils import formataddr
  13. # username,通过控制台创建的发信地址
  14. username = 'XXXXXXXX'
  15. # password,通过控制台创建的SMTP密码
  16. password = 'XXXXXXXX'
  17. # 自定义的回信地址,与控制台设置的无关。邮件推送发信地址不收信,收信人回信时会自动跳转到设置好的回信地址。
  18. replyto = 'XXXXXXXX'
  19. # 显示的To收信地址
  20. rcptto = ['address1@test.com', 'address2@test.com']
  21. # 显示的Cc收信地址
  22. rcptcc = ['address3@test.com', 'address4@test.com']
  23. # Bcc收信地址,密送人不会显示在邮件上,但可以收到邮件
  24. rcptbcc = ['address5@test.com', 'address6@test.com']
  25. # 全部收信地址,包含抄送地址,单次发送不能超过60人
  26. receivers = rcptto + rcptcc + rcptbcc
  27. # 构建alternative结构
  28. msg = MIMEMultipart('alternative')
  29. msg['Subject'] = Header('自定义信件主题')
  30. msg['From'] = formataddr(["自定义发信昵称", username]) # 昵称+发信地址(或代发)
  31. # list转为字符串
  32. msg['To'] = ",".join(rcptto)
  33. msg['Cc'] = ",".join(rcptcc)
  34. msg['Reply-to'] = replyto
  35. msg['Message-id'] = email.utils.make_msgid()
  36. msg['Date'] = email.utils.formatdate()
  37. # 若需要开启邮件跟踪服务,请使用以下代码设置跟踪链接头。
  38. # 首先域名需要备案,设置且已正确解析了CNAME配置;其次发信需要打Tag,此Tag在控制台已创建并存在,Tag创建10分钟后方可使用;
  39. # 设置跟踪链接头
  40. # 控制台创建的标签tagname
  41. # tagName = 'xxxxxxx'
  42. #
  43. # # OpenTrace对应值是字符串1,固定
  44. # trace = {
  45. # "OpenTrace": '1',
  46. # "LinkTrace": '1', #smtp新增点击跟踪
  47. # "TagName": tagName
  48. # }
  49. # jsonTrace = json.dumps(trace)
  50. # base64Trace = str(base64.b64encode(jsonTrace.encode('utf-8')), 'utf-8')
  51. # # print(base64Trace)
  52. # msg.add_header("X-AliDM-Trace", base64Trace)
  53. # 构建alternative的text/plain部分
  54. # textplain = MIMEText('自定义TEXT纯文本部分', _subtype='plain', _charset='UTF-8')
  55. # msg.attach(textplain)
  56. # 构建alternative的text/html部分
  57. texthtml = MIMEText('自定义HTML超文本部分', _subtype='html', _charset='UTF-8')
  58. msg.attach(texthtml)
  59. # 发送邮件
  60. try:
  61. # 若需要加密使用SSL,可以这样创建client
  62. # client = smtplib.SMTP_SSL('smtpdm.aliyun.com', 465)
  63. # SMTP普通端口为25或80
  64. client = smtplib.SMTP('smtpdm.aliyun.com', 80)
  65. # 开启DEBUG模式
  66. client.set_debuglevel(0)
  67. # 发件人和认证地址必须一致
  68. client.login(username, password)
  69. # 备注:若想取到DATA命令返回值,可参考smtplib的sendmail封装方法:
  70. # 使用SMTP.mail/SMTP.rcpt/SMTP.data方法
  71. # print(receivers)
  72. client.sendmail(username, receivers, msg.as_string()) # 支持多个收件人,最多60个
  73. client.quit()
  74. print('邮件发送成功!')
  75. except smtplib.SMTPConnectError as e:
  76. print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error)
  77. except smtplib.SMTPAuthenticationError as e:
  78. print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error)
  79. except smtplib.SMTPSenderRefused as e:
  80. print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)
  81. except smtplib.SMTPRecipientsRefused as e:
  82. print('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error)
  83. except smtplib.SMTPDataError as e:
  84. print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
  85. except smtplib.SMTPException as e:
  86. print('邮件发送失败, ', str(e))
  87. except Exception as e:
  88. print('邮件发送异常, ', str(e))