python 自动发送QQ邮箱

x33g5p2x  于2021-11-13 转载在 Python  
字(2.4k)|赞(0)|评价(0)|浏览(388)

一、授权码获取

开启它:

发送短信:

发送后点击我已发送:

把这个授权码复制下来保存起来,下次还可以用。

二、发送文本和附件

你只需要修改邮箱,授权码,当然如果你想发送附件也把附件路径加上即可。
python代码:

  1. # coding=gbk
  2. """
  3. 作者:川川
  4. @时间 : 2021/11/10 10:50
  5. 群:970353786
  6. """
  7. import smtplib
  8. from email.mime.text import MIMEText
  9. from email.mime.image import MIMEImage
  10. from email.mime.multipart import MIMEMultipart
  11. from email.mime.application import MIMEApplication
  12. # 写成了一个通用的函数接口,想直接用的话,把参数的注释去掉就好
  13. def send_email(msg_from, passwd, msg_to, text_content, file_path=None):
  14. msg = MIMEMultipart()
  15. subject = "python 实现邮箱发送邮件" # 主题
  16. text = MIMEText(text_content)
  17. msg.attach(text)
  18. # file_path = r'read.md' #如果需要添加附件,就给定路径
  19. if file_path: # 最开始的函数参数我默认设置了None ,想添加附件,自行更改一下就好
  20. docFile = file_path
  21. docApart = MIMEApplication(open(docFile, 'rb').read())
  22. docApart.add_header('Content-Disposition', 'attachment', filename=docFile)
  23. msg.attach(docApart)
  24. print('发送附件!')
  25. msg['Subject'] = subject
  26. msg['From'] = msg_from
  27. msg['To'] = msg_to
  28. try:
  29. s = smtplib.SMTP_SSL("smtp.qq.com", 465)
  30. s.login(msg_from, passwd)
  31. s.sendmail(msg_from, msg_to, msg.as_string())
  32. print("发送成功")
  33. except smtplib.SMTPException as e:
  34. print("发送失败")
  35. finally:
  36. s.quit()
  37. msg_from = '283****79@qq.com' # 发送方邮箱
  38. passwd = 'd******a' # 填入发送方邮箱的授权码(就是刚刚你拿到的那个授权码)
  39. msg_to = '283******9@qq.com' # 收件人邮箱,我是自己发给自己
  40. text_content = "hi,this is a demo!" # 发送的邮件内容
  41. file_path = 'read.md' # 需要发送的附件目录
  42. send_email(msg_from,passwd,msg_to,text_content,file_path)

运行:(收到邮箱)

三、继续升级

你是否可以在这基础上再做改动,比如爬取某个网页的主要内容发送到邮箱?爬虫有趣的东西多着呢!比如我自动填体温,把填报后的效果发送给我邮箱。
python代码:(txt里面为我的具体内容)

  1. # coding=gbk
  2. """
  3. 作者:川川
  4. @时间 : 2021/11/10 11:50
  5. 群:970353786
  6. """
  7. import smtplib
  8. from email.mime.text import MIMEText
  9. from email.mime.multipart import MIMEMultipart
  10. from email.mime.application import MIMEApplication
  11. def send_email(msg_from, passwd, msg_to, text_content):
  12. msg = MIMEMultipart()
  13. subject = "计算机自动填体温结果" # 主题
  14. text = MIMEText(text_content)
  15. msg.attach(text)
  16. msg['Subject'] = subject
  17. msg['From'] = msg_from
  18. msg['To'] = msg_to
  19. try:
  20. s = smtplib.SMTP_SSL("smtp.qq.com", 465)
  21. s.login(msg_from, passwd)
  22. s.sendmail(msg_from, msg_to, msg.as_string())
  23. print("发送成功")
  24. except smtplib.SMTPException as e:
  25. print("发送失败")
  26. finally:
  27. s.quit()
  28. msg_from = '28****579@qq.com' # 发送方邮箱
  29. passwd = 'dw****rodhda' # 填入发送方邮箱的授权码(就是刚刚你拿到的那个授权码)
  30. msg_to = '2****9579@qq.com' # 收件人邮箱
  31. with open("log_t.txt", "r",encoding="utf-8") as f: # 打开文件
  32. data = f.read() # 读取文件
  33. text_content = data # 发送的邮件内容
  34. send_email(msg_from,passwd,msg_to,text_content)

运行效果:

四、声明

自动邮箱发送仅仅用于个人学习练习,若用于其它等用途,后果自负,概不负责。

相关文章