首先,得有个mail.py类。该类封装了发送一个mail时需要设置的多个参数。代码如下:
'''
邮件类。用来给指定用户发送邮件。可指定多个收件人,可带附件。'''
import re
import smtplib
from email.mime.multipartimport MIMEMultipart
from email.mime.textimport MIMEText
from socketimport gaierror,error
from utils.logimport logger
class Email:
def __init__(self,server,sender,password,receiver,title,message =None,path =None,code = 'utf-8'):
'''
初始化Email
:param server: smtp服务器,必填
:param sender: 发件人,必填
:param password: 发件人密码,必填
:param receiver: 收件人,多收件人用“;”隔开,必填
:param title: 邮件标题,必填
:param message: 邮件正文,非必填
:param path: 附件路径,可传入list(多附件)或str(单个附件),非必填'''
self.title = title
self.message = message
self.files = path
self.msg = MIMEMultipart('related')
self.server = server
self.sender = sender
self.receiver = receiver
self.password = password
def _attach_file(self,att_file):
'''
将单个文件添加到附件列表中
:paramatt_file:
:return:
'''
att = MIMEText(open('%s' % att_file,'rb').read(),'plain','utf-8')
att['Content-Type'] ='application/octet-stream'
file_name = re.split(r'[\\]/',att_file)
att['Content-Disposition'] ='attachment;filename = "%s"'%file_name[-1]
self.msg.attach(att)
logger.info('attach file {}'.format(att_file))
def send(self):
self.msg['Subject'] =self.title
self.msg['From'] =self.sender
self.msg['To'] =self.receiver
#邮件正文
if self.message:
self.msg.attach(MIMEText(self.message))
#添加附件,支持多个附件(传入list),或者单个附件(传入str)
if self.files:
if isinstance(self.files,list):
for fin self.files:
self._attach_file(f)
elif isinstance(self.files,str):
self._attach_file(self.files)
#连接服务器并发送
try:
smtp_server = smtplib.SMTP(self.server,25)#连接server
except (gaierrorand error)as e:
logger.exception('邮件发送失败,无法连接到SMTP服务器,检查网络及SMTP服务器. %s',e)
else:
try:
smtp_server.login(self.sender,self.password)#发送者登录
except smtplib.SMTPAuthenticationErroras e:
logger.exception('用户名密码验证失败!%s',e)
else:
smtp_server.sendmail(self.sender,self.receiver.split(';'),self.msg.as_string())#发邮件
finally:
smtp_server.quit()#断开连接
logger.info('发送邮件"{0}"成功! 收件人:{1}。如果没有收到邮件,请检查垃圾箱,'
'同时检查收件人地址是否正确'.format(self.title, self.receiver))
其次,需要在case中调用该类的email函数:
其中:1为邮件的接收者;2为发送邮件的服务器;3为发送邮件者;4为发送者的授权密码(这里用的163邮箱,关于其授权密码怎么设置,自己去百度)
这里要注意的就是这个password,一定要是授权密码,而非登录密码!!!!
遗留问题:
发送邮件成功后,在收件箱中有该邮件,点击预览时发现有部分中文有乱码,但是下载下来看时又没有乱码。到目前为止,不知道预览中的乱码怎么解决。如图示: