邮箱发送邮件带附件格式,使用方法。
1.可以选择是否增加附加,如果不需要附件,只需要将附件的传参值为空即可。
2.邮件抄送功能鸡肋,如果想用抄送功能,把To和Cc合并全部发送。
3.可以把需要长改变参数取出,如email地址。
# !/usr/bin/env python # -*- coding: utf-8 -*- import smtplib import email.mime.multipart import email.mime.text from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase import email import base64 class send_mail: def __init__(self, From, To,Cc, pw, file_path, file_header, file_body): # 发送人 self.From = From # 收件人['aaa@a.com','bbb@a.com'] self.To = list(To) #抄送人 self.Cc = list(Cc) # 登录邮件密码base64.encodestring('明文')加密后密码 self.pw = pw # 文件具体路径(路径+文件名称) self.file_path = file_path # 标题头 self.file_header = file_header # 内容 self.file_body = file_body def login(self): server = smtplib.SMTP('邮箱域名 or ip') server.starttls() # pwd = base64.decodestring(self.pw) server.login(self.From, self.pw) try: receive = self.To #receive.extend(self.Cc) server.sendmail(self.From,self.To,self.atta()) finally: server.quit() def atta(self): main_msg = MIMEMultipart() # 内容 text_msg = MIMEText(self.file_body) main_msg.attach(text_msg) try: contype = 'application/octet-stream' maintype, subtype = contype.split('/', 1) data = open(self.file_path, 'rb') file_msg = MIMEBase(maintype, subtype) file_msg.set_payload(data.read()) data.close() email.encoders.encode_base64(file_msg) basename = os.path.basename(self.file_path.split('/')[-1]) file_msg.add_header('Content-Disposition', 'attachment', filename=basename) main_msg.attach(file_msg) except Exception as e: pass main_msg['From'] = self.From main_msg['To'] = ";".join(self.To) main_msg['Cc'] = ";".join(self.Cc) # 标题头 main_msg['Subject'] = self.file_header main_msg['Date'] = email.utils.formatdate() fullText = main_msg.as_string() return fullText if __name__ == '__main__': s = send_mail('发送邮箱', ['收件人邮箱'],['邮箱], '邮箱密码', '附件具体位置', '主题', '内容') s.login() print('发送成功!')