记录维维的每一篇Hello World

ffd1651c42f0a3fb200fef4b477febc.jpg


使用到的模板/库

  1. import os
  2. import smtplib
  3. import email

获取QQ邮箱授权码

发送QQ邮箱需要获取授权码,按以下步骤获取
image.png
image.png
image.png
image.png

填入信息

获取到授权码后,复制到以下代码中,也相应更改其他内容

  1. if __name__ == '__main__':
  2. u = '*******@qq.com' # 邮箱(本代码仅用于QQ邮箱)
  3. pwd = '*******' # 授权码(QQ邮箱中获取到的授权码)
  4. to = '*******@qq.com' # 收件人邮箱(想要发送的人)
  5. sub = 'python' # 邮箱主题(选填)
  6. from_n = '维维' # 发件人昵称(选填)
  7. to_n = '坠梦者' # 收件人昵称(选填)
  8. msg = '人生苦短,我用python' # 发送的消息
  9. # 附件路径(如果想要发送附件,填入相对应的绝对路径)
  10. path = 'D:\\python\\help.docx'

完整源码

  1. # -*- coding : utf-8-*-
  2. # Project: qq-email
  3. # Created by
  4. import os
  5. import smtplib
  6. from email.mime.application import MIMEApplication
  7. from email.mime.multipart import MIMEMultipart
  8. from email.mime.text import MIMEText
  9. from email.utils import formataddr
  10. class SendEmail:
  11. def __init__(self, user: str, password: str, user_name: str = "", subject: str = "") -> None:
  12. self.__user = user
  13. self.__password = password
  14. self.__fromName = user_name
  15. self.__subject = subject
  16. def send(self, to_people: str, message: str, to_name: str = "", subject: str = None, file_path: str = None):
  17. try:
  18. flag = True
  19. send_msg = MIMEMultipart()
  20. text = MIMEText(message, "plain", "utf-8")
  21. send_msg.attach(text)
  22. if file_path:
  23. enclosure = MIMEApplication(open(file_path, 'rb').read())
  24. enclosure.add_header('Content-Disposition', 'attachment', filename=os.path.split(file_path)[1])
  25. send_msg.attach(enclosure)
  26. send_msg['From'] = formataddr((self.__fromName, self.__user))
  27. send_msg['To'] = formataddr((to_name, to_people))
  28. send_msg['Subject'] = self.__subject if subject is None else subject
  29. send_srv = smtplib.SMTP_SSL("smtp.qq.com", 465)
  30. send_srv.login(self.__user, self.__password)
  31. send_srv.sendmail(self.__user, to_people, send_msg.as_string())
  32. # send_srv.quit()
  33. except Exception:
  34. # 会引发异常的情况太多,就采用最宽泛的写法
  35. flag = False
  36. finally:
  37. # 不管成功与否,都退出
  38. send_srv.quit()
  39. return flag
  40. if __name__ == '__main__':
  41. u = '*******@qq.com' # 邮箱(本代码仅用于QQ邮箱)
  42. pwd = '*******' # 授权码(QQ邮箱中获取到的授权码)
  43. to = '*******@qq.com' # 收件人邮箱(想要发送的人)
  44. sub = 'python' # 邮箱主题(选填)
  45. from_n = '维维' # 发件人昵称(选填)
  46. to_n = '坠梦者' # 收件人昵称(选填)
  47. msg = '人生苦短,我用python' # 发送的消息
  48. # 附件路径(如果想要发送附件,填入相对应的绝对路径)
  49. path = 'D:\\python\\help.docx'
  50. # 实例化
  51. mail = SendEmail(user=u, password=pwd, user_name=from_n, subject=sub)
  52. # 发送
  53. result = mail.send(to_people=to, message=msg, to_name=to_n, file_path=path)
  54. r = '发送成功' if result else '发送失败'
  55. print(r)


python环境

电脑:Windows10

python:3.8.8(建议3.7以上)