day12_框架一sendmail.py代碼
阿新 • • 發佈:2018-03-21
ati () def lena sof pat 郵件標題 main read
import smtplib,os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
class SendMail(object):
def __init__(self,username,passwd,recv,title,content,
file=None,ssl=False,
email_host=‘smtp.163.com‘,port=25,ssl_port=465):
‘‘‘
:param username: 用戶名
:param passwd: 密碼
:param recv: 收件人,多個要傳list [‘[email protected]‘,‘[email protected]]
:param title: 郵件標題
:param content: 郵件正文
:param file: 附件路徑,如果不在當前目錄下,要寫絕對路徑,默認沒有附件
:param ssl: 是否安全鏈接,默認為普通
:param email_host: smtp服務器地址,默認為163服務器
:param port: 非安全鏈接端口,默認為25
:param ssl_port: 安全鏈接端口,默認為465
‘‘‘
self.username = username #用戶名
self.passwd = passwd #密碼
self.recv = recv #收件人,多個要傳list [‘[email protected]‘,‘[email protected]]
self.title = title #郵件標題
self.content = content #郵件正文
self.file = file #附件路徑,如果不在當前目錄下,要寫絕對路徑
self.email_host = email_host #smtp服務器地址
self.port = port #普通端口
self.ssl = ssl #是否安全鏈接
self.ssl_port = ssl_port #安全鏈接端口
def send_mail(self):
msg = MIMEMultipart()
#發送內容的對象
if self.file:#處理附件的
file_name = os.path.split(self.file)[-1] # 只取文件名,不取路徑
try:
f = open(self.file, ‘rb‘).read()
except Exception as e:
raise Exception(‘附件打不開!!!!‘)
else:
att = MIMEText(f,"base64", "utf-8")
att["Content-Type"] = ‘application/octet-stream‘
#base64.b64encode(file_name.encode()).decode()
new_file_name=‘=?utf-8?b?‘ + base64.b64encode(file_name.encode()).decode() + ‘?=‘
#這裏是處理文件名為中文名的,必須這麽寫
att["Content-Disposition"] = ‘attachment; filename="%s"‘%(new_file_name)
msg.attach(att)
msg.attach(MIMEText(self.content))#郵件正文的內容
msg[‘Subject‘] = self.title # 郵件主題
msg[‘From‘] = self.username # 發送者賬號
msg[‘To‘] = ‘,‘.join(self.recv) # 接收者賬號列表
if self.ssl:
self.smtp = smtplib.SMTP_SSL(self.email_host,port=self.ssl_port)
else:
self.smtp = smtplib.SMTP(self.email_host,port=self.port)
#發送郵件服務器的對象
self.smtp.login(self.username,self.passwd)
try:
self.smtp.sendmail(self.username,self.recv,msg.as_string())
pass
except Exception as e:
print(‘出錯了。。‘,e)
else:
print(‘發送成功!‘)
self.smtp.quit()
if __name__ == ‘__main__‘:
m = SendMail(
username = ‘[email protected]‘,
passwd = ‘a123456‘,
recv = [‘[email protected]‘,‘[email protected]‘],
title = ‘美好的一天2018年3月21‘,
content = ‘哈哈哈啊哈哈哈哈0321‘,
file = r‘C:\Users\sun\Desktop\測試用例.xlsx‘,ssl=True,
)
m.send_mail()
day12_框架一sendmail.py代碼