【python】python 自动发邮件

一、一般发邮件的方法

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

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

然后,通过SMTP发出去:

 1 # coding:utf-8
 2 import smtplib
 3 from email.mime.text import MIMEText
 4 
 5 
 6 class SendMail:
 7 
 8     def send_mail(self, receiver_list, sub, content):
 9         host = "smtp.qq.com"            # 服务器地址
10         sender = "123@qq.com"     # 发件地址
11         password = "pwd"
12         #邮件内容
13         message = MIMEText(content, _subtype='plain', _charset='utf-8')
14         message['Subject'] = sub   # 邮件主题
15         message['From'] = sender   
16         message['To'] = ";".join(receiver_list)   # 收件人之间以;分割
17         server = smtplib.SMTP()
18         # 连接服务器
19         server.connect(host=host)
20         # 登录
21         server.login(user=sender, password=password)
22         server.sendmail(from_addr=sender, to_addrs=receiver_list, msg=message.as_string())
23         server.close()
24 
25 if __name__ == '__main__':
26     send = SendMail()
27     receive = ["123qq.com", "456@163.com"]
28     sub = "测试邮件"
29     content = "测试邮件"
30     send.send_mail(receive, sub, content)

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

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

 

二、利用yagmail库发送邮件

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

首先需要安装库: pip install yagmail

然后:

 1 import yagmail
 2 
 3 
 4 class SendMail:
 5 
 6     def send_mail(self, receiver_list, sub, content, attach=None):
 7         host = "smtp.qq.com"
 8         sender = "983@qq.com"
 9         password = "ryg"
10         # 连接服务器
11         yag = yagmail.SMTP(user=sender, password=password, host=host)
12         # 邮件内容
13         yag.send(to=receiver_list, subject=sub, contents=content, attachments=attach)
14 
15 
16 if __name__ == '__main__':
17     send = SendMail()
18     receive = ["983@qq.com", "513@163.com"]
19     sub = "测试邮件"
20     content = ["yagmail测试邮件", "\n", "hello word"]
21     attch = "C:\\Users\\Administrator\\Desktop\\10.jpg"
22     send.send_mail(receive, sub, conten8t, attch)

 

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

少写了好几行代码

 

posted @ 2018-10-31 23:28  dhs94  阅读(215)  评论(0编辑  收藏  举报