Python自动发送邮件--smtplib模块

 1 import smtplib
 2 from email.mime.multipart import MIMEMultipart
 3 from email.mime.text import MIMEText
 4 from email.mime.application import MIMEApplication
 5 from email.mime.image import MIMEImage
 6 
 7 account='[email protected]'  #发件人
 8 pwd = '*******'    #第三方授权码,需登录qq mail web页,开通设置。
 9 to = ['[email protected]','[email protected]','[email protected]'] # 发送给多个收件人
10 host='smtp.qq.com'      #主机
11 atta_path = r'C:\Users\Administrator\Desktop\testdata.txt'  #附件路径与名称
12 name='要展示的文件名.txt'      #附件显示的名称
13 img_path = r'C:\Users\Administrator\Desktop\dog.jpg'    #显示在正文中的图片
14 
15 # 这是正文显示部分,其中img标签中的src的cid:0,这个0与下文的content-ID对应。
16 
17 content='''
18 

19 Project:

mobile test

20

Tester:

fish

21

Date:

2019/12/12

22

Result:

Pass

23

For morn details,you can check Test Result

24 picture 25 26 ''' 27 def sendmail(): 28 29 ret = True 30 try: 31 msg = MIMEMultipart() 32 msg['Subject'] = 'Test' 33 msg['From'] = account 34 msg['To'] = ';'.join(to) 35 36 #将图片显示在邮件正文中 37 fp=open(img_path,'rb') 38 img= MIMEImage(fp.read()) 39 img.add_header('Content-ID', '0') 40 msg.attach(img) 41 42 #邮件中显示正文 43 part_text = MIMEText(content,'html','UTF-8') 44 msg.attach(part_text) 45 46 47 #这是附件部分,不同类型的附件,只需修改名称、位置、要显示的名字 48 part_att = MIMEApplication(open(atta_path,'rb').read()) 49 part_att.add_header('Content-Disposition', 'attachment', filename=name) 50 msg.attach(part_att) 51 52 #实例化一个SMTP的对象,然后登录、发送邮件 53 s = smtplib.SMTP(host,timeout= 30) 54 s.login(account,pwd) 55 s.sendmail(account,to,msg.as_string()) 56 s.close() 57 except Exception as e: 58 ret = False 59 resaon = str(e) 60 return ret 61 62 ret = sendmail() 63 64 if ret: 65 print('send successfully') 66 else: 67 print('Error: send failed: ',reason)

如上的代码,可实现一个简单的邮件自动发送,且不会显示在垃圾箱中。

你可能感兴趣的:(Python自动发送邮件--smtplib模块)