python实现邮件循环自动发件

前端之家收集整理的这篇文章主要介绍了python实现邮件循环自动发件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

邮件是一种很常见的操作,本篇主要介绍一下如何用python实现自动发件。

  1. import smtplib
  2. from email.mime.text MIMEText
  3. from email.mime.multipart MIMEMultipart
  4. from email.header Header
  5. from email.mime.image MIMEImage
  6. time
  7. mail_host="smtp.126.com"
  8. mail_user=xxx@126.com
  9. mail_pass=******#注意如果邮箱开启了授权码,此处要填写授权码,否则会报smtplib.SMTPAuthenticationError: (535,b'Error: authentication Failed')
  10. sender=
  11. receiver = ['邮箱1',邮箱2']群发邮件
  12. for i in range(n):自定义循环发多少遍
  13. try:
  14. message = MIMEMultipart()
  15. message[From"] = Header(sender)
  16. message[To"] = ,'.join(receiver)
  17. message[Subject"] = Header(主题",1)">utf-8").encode()主题
  18. message.attach(MIMEText(正文plain"))正文
  19. """
  20. 定附件
  21. """
  22. att = MIMEText(open(rC:\Users\Administrator\Desktop\1.txt').read(),1)">base64)
  23. att[Content-Typeapplication/octet-stream
  24. att.add_header(Content-Dispositionattachment1.txt")这一步可避免文件不能正常打开
  25. message.attach(att)
  26. 构造图片(以附件形式上传
  27. image = MIMEImage(open(rC:\Users\Administrator\Desktop\1.jpgrb).read())
  28. image.add_header(Content-ID<image1>')可避免图片不能正常打开
  29. image[attachment; filename="picture.jpg"
  30. message.attach(image)
  31. 发送邮件
  32. smtp = smtplib.SMTP_SSL(host=mail_host)
  33. smtp.connect(host=mail_host,port=465)
  34. smtp.login(mail_user,mail_pass)
  35. smtp.sendmail(sender,message['].split(),message.as_string())
  36. print(在%s第" % ctime(),str(i+1),1)">封邮件发送)
  37. smtp.quit()
  38. except smtplib.SMTPException as e:
  39. raise e

最终实现

在这里插入图片描述

 

本文首发于python黑洞网博客园同步更新

猜你在找的Python面试题相关文章