import os
import smtplib
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class SendEmail(object):
def __init__(self, username, passwd, recv, title, content,
file=None, ssl=False,
email_host='smtp.163.com', port=25, 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服務器地址,163的爲smtp.163.com
self.port = port # 普通端口
self.ssl = ssl # 是否安全鏈接
self.ssl_port = ssl_port # 安全鏈接端口
def send_email(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('附件打不開!!!!%s' % e)
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 = SendEmail(
username='@163.com',
passwd='',
recv=[''],
title='',
content='測試發送郵件',
file=r'E:\a.png',
ssl=True,
)
m.send_email()