python 发邮件实例

 1 import smtplib    
 2 from email.mime.multipart import MIMEMultipart    
 3 from email.mime.text import MIMEText    
 4 from email.mime.image import MIMEImage 
 5 from email.header import Header   
 6     
 7 #设置smtplib所需的参数
 8 #下面的发件人,收件人是用于邮件传输的。
 9 smtpserver = 'smtp.126.com'
10 username = 'XXX@126.com'
11 #此处的密码为客户端授权密码
12 password='****'      
13 sender='XXX@126.com'
14 #receiver='XXX@126.com'
15 #收件人为多个收件人
16 receiver=['XXX1@qq.com','XXX2@qq.com']
17 
18 subject = 'Python email test'
19 #通过Header对象编码的文本,包含utf-8编码信息和Base64编码信息。以下中文名测试ok
20 #subject = '中文标题'
21 #subject=Header(subject, 'utf-8').encode()
22     
23 #构造邮件对象MIMEMultipart对象
24 #下面的主题,发件人,收件人,日期是显示在邮件页面上的。
25 msg = MIMEMultipart('mixed') 
26 msg['Subject'] = subject
27 msg['From'] = 'XXX@126.com <XXX@126.com>'
28 #msg['To'] = 'XXX@126.com'
29 #收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
30 msg['To'] = ";".join(receiver) 
31 #msg['Date']='2012-3-16'
32 
33 #构造文字内容   
34 text = "Hi!
How are you?
Here is the link you wanted:
http://www.baidu.com"    
35 text_plain = MIMEText(text,'plain', 'utf-8')    
36 msg.attach(text_plain)    
37 
38 #构造图片链接
39 #sendimagefile=open(r'D:pythontest	estimage.png','rb').read()
40 #image = MIMEImage(sendimagefile)
41 #image.add_header('Content-ID','<image1>')
42 #image["Content-Disposition"] = 'attachment; filename="testimage.png"'
43 #msg.attach(image)
44 
45 #构造html
46 #发送正文中的图片:由于包含未被许可的信息,网易邮箱定义为垃圾邮件,报554 DT:SPM :<p><img src="cid:image1"></p>
47 html = """
48 <html>  
49   <head></head>  
50   <body>  
51     <p>Hi!<br>  
52        How are you?<br>  
53        Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> 
54     </p> 
55   </body>  
56 </html>  
57 """    
58 text_html = MIMEText(html,'html', 'utf-8')
59 text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"'   
60 msg.attach(text_html)    
61 
62 
63 #构造附件
64 #sendfile=open(r'D:pythontest1111.txt','rb').read()
65 #text_att = MIMEText(sendfile, 'base64', 'utf-8') 
66 #text_att["Content-Type"] = 'application/octet-stream'  
67 #以下附件可以重命名成aaa.txt  
68 #text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"'
69 #另一种实现方式
70 #text_att.add_header('Content-Disposition', 'attachment', filename='aaa.txt')
71 #以下中文测试不ok
72 #text_att["Content-Disposition"] = u'attachment; filename="中文附件.txt"'.decode('utf-8')
73 #msg.attach(text_att)    
74        
75 #发送邮件
76 smtp = smtplib.SMTP()    
77 smtp.connect('smtp.126.com')
78 #我们用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。
79 #smtp.set_debuglevel(1)  
80 smtp.login(username, password)    
81 smtp.sendmail(sender, receiver, msg.as_string())    
82 smtp.quit()

摘自 https://www.cnblogs.com/yufeihlf/p/5726619.html

原文地址:https://www.cnblogs.com/allen-zqw/p/9720683.html