全部产品

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

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

  1. # -*- coding:utf-8 -*-
  2. import smtplib
  3. import email
  4. from email.mime.multipart import MIMEMultipart
  5. from email.mime.text import MIMEText
  6. from email.mime.image import MIMEImage
  7. from email.mime.base import MIMEBase
  8. from email.mime.application import MIMEApplication
  9. from email.header import Header
  10. # 发件人地址,通过控制台创建的发件人地址
  11. username = '***'
  12. # 发件人密码,通过控制台创建的发件人密码
  13. password = '***'
  14. # 自定义的回复地址
  15. replyto = '***'
  16. # 收件人地址或是地址列表,支持多个收件人,最多30个
  17. #rcptto = ['***', '***']
  18. rcptto = '***'
  19. # 构建alternative结构
  20. msg = MIMEMultipart('alternative')
  21. msg['Subject'] = Header('自定义信件主题')
  22. msg['From'] = '%s <%s>' % (Header('自定义发信昵称'), username)
  23. msg['To'] = rcptto
  24. msg['Reply-to'] = replyto
  25. msg['Message-id'] = email.utils.make_msgid()
  26. msg['Date'] = email.utils.formatdate()
  27. # 构建alternative的text/plain部分
  28. textplain = MIMEText('自定义TEXT纯文本部分', _subtype='plain', _charset='UTF-8')
  29. msg.attach(textplain)
  30. # 构建alternative的text/html部分
  31. texthtml = MIMEText('自定义HTML超文本部分', _subtype='html', _charset='UTF-8')
  32. msg.attach(texthtml)
  33. # 发送邮件
  34. try:
  35. client = smtplib.SMTP()
  36. #python 2.7以上版本,若需要使用SSL,可以这样创建client
  37. #client = smtplib.SMTP_SSL()
  38. #SMTP普通端口为25或80
  39. client.connect('smtpdm.aliyun.com', 25)
  40. #开启DEBUG模式
  41. client.set_debuglevel(0)
  42. client.login(username, password)
  43. #发件人和认证地址必须一致
  44. #备注:若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法:
  45. # 使用SMTP.mail/SMTP.rcpt/SMTP.data方法
  46. client.sendmail(username, rcptto, msg.as_string())
  47. client.quit()
  48. print('邮件发送成功!')
  49. except smtplib.SMTPConnectError as e:
  50. print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error)
  51. except smtplib.SMTPAuthenticationError as e:
  52. print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error)
  53. except smtplib.SMTPSenderRefused as e:
  54. print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)
  55. except smtplib.SMTPRecipientsRefused as e:
  56. print('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error)
  57. except smtplib.SMTPDataError as e:
  58. print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
  59. except smtplib.SMTPException as e:
  60. print('邮件发送失败, ', str(e))
  61. except Exception as e:
  62. print('邮件发送异常, ', str(e))