第一种是最常见的,smtp发送
import smtplibimport sysimport tracebackfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport osdef sendEmail(mail_sender, to_list, sub, content, attach_list = [], _subtype="html"):"""使用smtp发送邮件:param mail_sender: 发件人:param to_list: 收件人列表,用,间隔:param sub: 主题:param content: 内容:param attach_list:附件:param _subtype: 读取内容用的方式,不传html的话改成plain:return:"""msg = MIMEMultipart()msg['subject'] = submsg['From'] = mail_sendermsg['To'] = to_listtry:msg.attach(MIMEText(content, _subtype,'utf-8')) #用html的方法是更方便于word文档作为内容发送,可以先讲word转换成html,然后写入其中s = smtplib.SMTP('123.com', 25)# s.login()s.starttls()if attach_list:for att_path in attach_list:path_arr = att_path.split(os.path.sep)file_name = path_arr[len(path_arr) - 1]att1 = MIMEText(open(att_path,'rb').read(), 'base64','utf-8')att1.add_header('Content-Disposition', 'attachment', filename=file_name) #用这个方法可以避免附件乱码msg.attach(att1)s.sendmail(mail_sender, to_list.split(u','), msg.as_string())s.close()print("999921||业务数据处理||邮件发送成功")return Trueexcept Exception as e:sys.stderr.write("999931||{}".format(traceback.format_exc(limit=None, chain=True)))sys.stderr.write("0001")return False
第二种是用outlook发送的,这个大家借鉴使用
import osfrom time import sleepimport autoit as auimport win32com.clientclass OutlookUtills:def __init__(self):outlook = win32com.client.Dispatch("outlook.Application ")# outlook.Visible = Trueself.mail = outlook.CreateItem(0)self.mail.Display()def sendEmail(self, addressee, subiect, AttachmentsPath=[], body=None):"""若body为默认值None则自动粘贴剪切板中内容进行发送:param addressee: 收件人:param subiect: 主题:param AttachmentsPath: 附件名称:param body: 正文:return:"""self.mail. To = addresseeself.mail.subject = subiectif AttachmentsPath == []:print("该邮件无附件")else:for Attachments in AttachmentsPath:self.mail.Attachments.Add(Attachments)print("地址:{},附件添加成功!!")sleep(2)if body == None:self.mail.body = ""au.send('^v')print("正文已从剪切板拷贝")else:self.mail.body = bodyprint("正文由函数进行输入")sleep(1)self.mail.Send()if __name__ == '__main__':my_outlook = OutlookUtills()
第三种是正文需要用到表格的,我在这里给大家一个示例,具体表格怎么改自行发挥
import smtplibfrom email.mime.text import MIMETextfrom email.header import Headerclass Mail:def __init__(self):# 第三方 SMTP 服务self.mail_host = "smtp.qq.com"# 填写邮箱服务器:这个是qq邮箱服务器,直接使用smtp.qq.comself.mail_pass = "ahlwsnkajalubeif"# 填写在qq邮箱设置中获取的授权码self.sender = '1004983289@qq.com'# 填写邮箱地址self.receivers = ['tianyi.zhang@kingstarfintech.com']# 填写收件人的邮箱,QQ邮箱或者其他邮箱,可多个,中间用,隔开def send(self):self.mail_host = "smtp.qq.com"# 填写邮箱服务器:这个是qq邮箱服务器,直接使用smtp.qq.comself.mail_pass = "ahlwsnkajalubeif"# 填写在qq邮箱设置中获取的授权码self.sender = '1004983289@qq.com'# 填写邮箱地址self.receivers = ['tianyi.zhang@kingstarfintech.com']# 填写收件人的邮箱,QQ邮箱或者其他邮箱,可多个,中间用,隔开insert = "152371200010240002 潘金莲 tar 152371200010240002.tar 20220426-1545 否 152371200010240002 潘金莲 tar 152371200010240002.tar 20220426-1545 否 "head = \"""table {border-collapse: collapse;border: 2px solid #a19da2;/*居中显示整个表格*/margin: auto;}table thead {border: 2px solid #91c6e1;background: #f1f1f1;padding: 10px 10px 10px 10px;color: #333333;}table tbody {border: 2px solid #91c6e1;padding: 10px 10px 10px 10px;}table tr {}table th {vertical-align: top;font-size: 14px;padding: 10px 10px 10px 10px;color: #105de3;font-family: arial;text-align: center;}table td {text-align: center;padding: 10px 10px 10px 10px;}body {font-family: 宋体;}h1 {color: #5db446}div.header h2 {color: #0002e3;font-family: 黑体;}div.content h2 {text-align: center;font-size: 28px;text-shadow: 2px 2px 1px #de4040;color: #fff;font-weight: bold;background-color: #008eb7;line-height: 1.5;margin: 20px 0;box-shadow: 10px 10px 5px #888888;border-radius: 5px;}h3 {font-size: 22px;background-color: rgba(0, 2, 227, 0.71);text-shadow: 2px 2px 1px #de4040;color: rgba(239, 241, 234, 0.99);line-height: 1.5;}h4 {color: #e10092;font-family: 楷体;font-size: 20px;text-align: center;}td img {/*width: 60px;*/max-width: 300px;max-height: 300px;}"""body = \"""表格中的数据为当天云开户信息下载及CRM上传情况
身份证号 姓名 文件类型 文件名 上传时间 是否上传成功 掌厅不存在身份证不一致情况
""".format(insert)html_msg = "" + head + body + ""html_msg = html_msg.replace('\n', '').encode("utf-8")message = MIMEText(html_msg, 'html', 'utf-8')message['From'] = Header("小胖子xpp", 'utf-8')#邮件发送者姓名message['To'] = Header("小胖子xpp", 'utf-8')#邮件接收者姓名subject = '测试'#发送的主题message['Subject'] = Header(subject, 'utf-8')try:smtpObj = smtplib.SMTP_SSL(self.mail_host, 465) #建立smtp连接,qq邮箱必须用ssl边接,因此边接465端口smtpObj.login(self.sender, self.mail_pass)#登陆smtpObj.sendmail(self.sender, self.receivers, message.as_string())#发送smtpObj.quit()print('发送成功!!')except smtplib.SMTPException as e:print('发送失败!!')if __name__ == '__main__':mail = Mail()mail.send()