python自动发送邮件

python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。

1. 基本流程如下:

 1 #coding=utf-8
 2 import smtplib
 3 from email.mime.text import MIMEText
 4 from email.header import Header
 5 
 6 def send_email(SMTP_host, from_account, from_password, to_account, subject, content):
 7     # 1. 实例化SMTP
 8     smtp = smtplib.SMTP()
 9 
10     # 2. 链接邮件服务器
11     smtp.connect(SMTP_host)
12 
13     # 3. 配置发送邮箱的用户名和密码
14     smtp.login(from_account, from_password)
15 
16     # 4. 配置发送内容msg
17     msg = MIMEText(content, 'plain', 'utf-8')
18     msg['Subject'] = Header(subject,'utf-8')
19     msg['From'] = from_account
20     msg['To'] = to_account
21 
22     # 5. 配置发送邮箱,接受邮箱,以及发送内容
23     smtp.sendmail(from_account, to_account, msg.as_string())
24 
25     # 6. 关闭邮件服务
26     smtp.quit()
27 
28 if __name__ == '__main__':
29     send_email("smtp.163.com", "from_account", "from_pssword","to_account", "I want to talk to u", "In this semester")

2. smtplib模块

  • smtplib.SMTP():实例化SMTP()
  • connect(host,port):
    • host:指定连接的邮箱服务器。常用邮箱的smtp服务器地址如下:新浪邮箱:smtp.sina.com,新浪VIP:smtp.vip.sina.com,搜狐邮箱:smtp.sohu.com,126邮箱:smtp.126.com,139邮箱:smtp.139.com,163网易邮箱:smtp.163.com。
    • port:指定连接服务器的端口号,默认为0.
  • login(user,password):
    • user:登录邮箱的用户名。
    • password:登录邮箱的密码
  • sendmail(from_addr,to_addrs,msg,...):
    • from_addr:邮件发送者地址
    • to_addrs:邮件接收者地址。字符串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'
    • msg:发送消息:邮件内容。一般是msg.as_string():as_string()是将msg(MIMEText对象或者MIMEMultipart对象)变为str。
  • quit():用于结束SMTP会话。

3. email模块

email模块下有mime包,mime英文全称为“Multipurpose Internet Mail Extensions”,即多用途互联网邮件扩展,是目前互联网电子邮件普遍遵循的邮件技术规范。

该mime包下常用的有三个模块:text,image,multpart

3.1 导入方法:

1 from email.mime.multipart import MIMEMultipart    
2 from email.mime.text import MIMEText    
3 from email.mime.image import MIMEImage

其中:

  • 构造一个邮件对象就是一个Message对象
  • 如果构造一个MIMEText对象,就表示一个文本邮件对象
  • 如果构造一个MIMEImage对象,就表示一个作为附件的图片
  • 要把多个对象组合起来,就用MIMEMultipart对象
  • MIMEBase可以表示任何对象。它们的继承关系如下:
Message
+- MIMEBase
   +- MIMEMultipart
   +- MIMENonMultipart
      +- MIMEMessage
      +- MIMEText
      +- MIMEImage

3.2 传送文本邮件

邮件发送程序为了防止有些邮件阅读软件不能显示处理HTML格式的数据,通常都会用两类型分别为"text/plain"和"text/html"(如果发送内容为中文,需要选择“plain”,要不然无法显示)

构造MIMEText对象时,第一个参数是邮件正文,第二个参数是MIME的subtype,最后一定要用utf-8编码保证多语言兼容性。

3.2.1 添加普通文件

1 text = "This is a text
Here is the link you want:
http:\www.baidu.com"
2 msg = MINEText(text, 'plain', utf-8)

3.2.2 添加超文本

 1 html = """
 2 <html>  
 3   <body>  
 4     <p> 
 5        Here is the <a href="http://www.baidu.com">link</a> you wanted.
 6     </p> 
 7   </body>  
 8 </html>  
 9 """    
10 msg = MIMEText(html,'html', 'utf-8')  

3.2.3添加附件

1 sendfile = open('D:\python\sendfile.txt', 'rb').read()
2 msg = MINEText(sendfile, 'base64', 'utf-8')
3 msg['Content-type'] = 'application/octet-stream'
4 msg['Content-Disposition'] = 'attachment;filename= "文件显示名字.txt"'

3.2.4 添加图片

1 sendimagefile=open(r'D:pythontest	estimage.png','rb').read()
2 msg = MIMEImage(sendimagefile)
3 msg.add_header('Content-ID','<image1>')

4. 自动发送测试报告的邮件

 1 def send_report():
 2    # 一、获取最新的报告
 3    #  1. 获取report目录下的所有文件,结果以列表形式返回
 4    case_list = os.listdir(report_dir)
 5    # 2. 对case_list中所有元素按时间从大到小排序
 6    case_list.sort(key=lambda fn: os.path.getmtime(report_dir + "\" + fn)
 7         if not os.path.isdir(report_dir + "\" + fn) else 0)
 8    # 3. 获取最新报告的绝对路径
 9    print("The latest report:" + case_list[-1])
10    latest_report = os.path.join(report_dir, case_list[-1])
11    print(latest_report)
12 
13    # 二、发送邮件
14    send_email("smtp.163.com", "xx", "xx","xx", "消费者登录测试报告", latest_report)
原文地址:https://www.cnblogs.com/lesleysbw/p/5897224.html