【python】python 自动发邮件

时间:2022-12-21 21:17:49

一、一般发邮件的方法

Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。

注意到构造MIMETEXT对象时,第一个参数就是邮件正文,第二个参数是MIME的subtype,传入'plain'表示纯文本,最终的MIME就是‘text/plain’,最后一定要用utf-8编码保证多语言兼容性。

然后,通过SMTP发出去:

 # coding:utf-8
import smtplib
from email.mime.text import MIMEText class SendMail: def send_mail(self, receiver_list, sub, content):
host = "smtp.qq.com" # 服务器地址
sender = "123@qq.com" # 发件地址
password = "pwd"
#邮件内容
message = MIMEText(content, _subtype='plain', _charset='utf-8')
message['Subject'] = sub # 邮件主题
message['From'] = sender
message['To'] = ";".join(receiver_list) # 收件人之间以;分割
server = smtplib.SMTP()
# 连接服务器
server.connect(host=host)
# 登录
server.login(user=sender, password=password)
server.sendmail(from_addr=sender, to_addrs=receiver_list, msg=message.as_string())
server.close() if __name__ == '__main__':
send = SendMail()
receive = ["123qq.com", "456@163.com"]
sub = "测试邮件"
content = "测试邮件"
send.send_mail(receive, sub, content)

其实,这段代码也并不复杂,只要你理解使用过邮箱发送邮件,那么以下问题是你必须要考虑的:

  • 你登录的邮箱帐号/密码
  • 对方的邮箱帐号
  • 邮件内容(标题,正文,附件)
  • 邮箱服务器(SMTP.xxx.com/pop3.xxx.com)

二、利用yagmail库发送邮件

yagmail 可以更简单的来实现自动发邮件功能。

首先需要安装库: pip install yagmail

然后:

 import yagmail

 class SendMail:

     def send_mail(self, receiver_list, sub, content, attach=None):
host = "smtp.qq.com"
sender = "983@qq.com"
password = "ryg"
# 连接服务器
yag = yagmail.SMTP(user=sender, password=password, host=host)
# 邮件内容
yag.send(to=receiver_list, subject=sub, contents=content, attachments=attach) if __name__ == '__main__':
send = SendMail()
receive = ["983@qq.com", "513@163.com"]
sub = "测试邮件"
content = ["yagmail测试邮件", "\n", "hello word"]
attch = "C:\\Users\\Administrator\\Desktop\\10.jpg"
send.send_mail(receive, sub, conten8t, attch)

另外,附件也可以之间写在content中,即conten = ["yagmail测试邮件", "\n", "hello word", "C:\\Users\\Administrator\\Desktop\\10.jpg"]

少写了好几行代码

【python】python 自动发邮件