使用python发送邮件, 解决了邮件不能群发问题
1 #!/usr/bin/env python 2 #-*- coding:utf8 -*- 3 4 ''' 5 Created on 2019年3月17日 6 @author: perilong 7 ''' 8 import smtplib 9 # 发送字符串的邮件 10 from email.mime.text import MIMEText 11 # 处理多种形态的邮件主体我们需要 MIMEMultipart 类 12 from email.mime.multipart import MIMEMultipart 13 #处理图片需要 MIMEImage 类 14 from email.mime.image import MIMEImage 15 from email.mime.application import MIMEApplication 16 17 18 #------------------------设置服务器信息------------------------ 19 fromAddr = '********@qq.com' # 邮件发送方地址 20 password = '**********' # 邮箱授权码 21 toAddrs = '********@qq.com' # 邮件单发 22 toAddrs = ['******@qq.com', '*******@qq.com'] # 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发 23 24 25 #------------------------添加邮件主题及收发信息------------------------ 26 # 初始化邮件内容 27 message = MIMEMultipart() 28 # 邮件主题 29 message['Subject'] = 'first python auto email' 30 # 发送方信息 31 message['From'] = fromAddr 32 # 接收方信息 33 message['To'] = ','.join(toAddrs) # 邮件群发 34 35 36 #---------------------------设置邮件内容----------------------------- 37 # -----文字部分----- 38 part = MIMEText('hello, perilong', 'plain', 'utf-8') 39 40 # -----附件部分----- 41 # xlsx 42 partXLSX = MIMEApplication(open('D:/attach/1.xlsx', 'rb').read()) 43 partXLSX.add_header('Content-Disposition', 'attachment', filename='D:/attach/1.xlsx') 44 45 # doc 46 partDOC = MIMEApplication(open('D:/attach/1.docx', 'rb').read()) 47 partDOC.add_header('Content-Disposition', 'attachment', filename='D:/attach/1.docx') 48 49 # pdf 50 partPDF = MIMEApplication(open('D:/attach/PythonProject.pdf', 'rb').read()) 51 partPDF.add_header('Content-Disposition', 'attachment', filename='D:/attach/PythonProject.pdf') 52 53 # jpg 54 partJPG = MIMEApplication(open('D:/attach/1.jpg', 'rb').read()) 55 partJPG.add_header('Content-Disposition', 'attachment', filename='D:/attach/1.jpg') 56 57 58 #---------------------------添加邮件内容和附件----------------------------- 59 message.attach(part) 60 message.attach(partXLSX) 61 message.attach(partDOC) 62 message.attach(partPDF) 63 message.attach(partJPG) 64 65 #---------------------------登录邮箱并发送邮件----------------------------- 66 try: 67 s = smtplib.SMTP('smtp.qq.com', timeout=300) # 连接smtp服务器, 默认端口25 68 s.login(fromAddr, password) 69 s.sendmail(fromAddr, toAddrs, message.as_string()) # 发送邮件 70 print '邮件发送成功' 71 except Exception as e: 72 print '邮件发送失败' 73 s.close()
参考文章: https://blog.csdn.net/qq_20417499/article/details/80566265