郵箱發送郵件帶附件格式,使用方法。
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('發送成功!')
