1. 程式人生 > >day10_發送郵件終極版

day10_發送郵件終極版

郵件標題 mail try 工作表 cep ffice object blog raise

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=‘xxxx‘,
recv=[‘[email protected]‘,‘[email protected]‘],
title=‘新鞋的發送郵件‘,
content=‘哈哈哈啊哈哈哈哈‘,
file=r‘C:\Users\bjniuhanyang\Desktop\新建 Microsoft Office Excel 工作表.xlsx‘,ssl=True,
)
m.send_mail()



day10_發送郵件終極版