郵箱發送郵件帶附件格式,使用方法。python
1.能夠選擇是否增長附加,若是不須要附件,只須要將附件的傳參值爲空便可。app
2.郵件抄送功能雞肋,若是想用抄送功能,把To和Cc合併所有發送。ui
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('發送成功!')