加载中...

菜谱 4:发送带图片的邮件


我们平时需要使用 Python 发送各类邮件,这个需求怎么来实现?答案其实很简单,smtplib 和 email库可以帮忙实现这个需求。smtplib 和 email 的组合可以用来发送各类邮件:普通文本,HTML 形式,带附件,群发邮件,带图片的邮件等等。我们这里将会分几节把发送邮件功能解释完成。

smtplib 是 Python 用来发送邮件的模块,email 是用来处理邮件消息。

发送带图片的邮件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage:

  1. import smtplib
  2. from email.mime.multipart import MIMEMultipart
  3. from email.mime.text import MIMEText
  4. from email.mime.image import MIMEImage
  5. sender = '***'
  6. receiver = '***'
  7. subject = 'python email test'
  8. smtpserver = 'smtp.163.com'
  9. username = '***'
  10. password = '***'
  11. msgRoot = MIMEMultipart('related')
  12. msgRoot['Subject'] = 'test message'
  13. msgText = MIMEText(
  14. ''' Some HTML text and an image.good!''', 'html', 'utf-8')
  15. msgRoot.attach(msgText)
  16. fp = open('/Users/1.jpg', 'rb')
  17. msgImage = MIMEImage(fp.read())
  18. fp.close()
  19. msgImage.add_header('Content-ID', '')
  20. msgRoot.attach(msgImage)
  21. smtp = smtplib.SMTP()
  22. smtp.connect(smtpserver)
  23. smtp.login(username, password)
  24. smtp.sendmail(sender, receiver, msgRoot.as_string())
  25. smtp.quit()

注意:这里的代码并没有把异常处理加入,需要读者自己处理异常。


还没有评论.