本篇文章给大家带来的内容是关于python发送邮件smtp的详细介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
如何使用python将生成的测试报告以邮件附件的形式进行发送呢?
一、概要smtp(simple mail transfer protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。python的smtplib提供了一种很方便的途径发送电子邮件,它对smtp协议进行了简单的封装。
python对smtp支持有smtplib和email两个模块。其中email负责构造邮件,smtplib则负责发送邮件。
来理一理python发送一个未知mime类型的文件附件基本思路:
0、前提:导入邮件发送模块 from email.mime.text import mimetext from email.mime.multipart import mimemultipart import smtplib1、构造mimemultipart对象作为根容器2、构造mimetext对象作为邮件显示内容并附加到根容器 a、读入文件内容并格式化 b、设置附件头3、设置根容器属性4、得到格式化后的完整文本5、用smtp发送邮件6、封装成sendemail类。
二、邮件发送要素同时想想我们要发送邮件的几个要素:
1、服务器。以qq邮箱举例,则为smtp.qq.com2、端口号。有465和587,请使用5873、发送者。4、密码。密码总不能直接写在文件里吧?哈哈,这里需要使用qq邮箱获取授权码。5、收件人。(可能还不止一个)6、发送邮件的主题subject。7、邮件文本内容。8、附件。
因为之前写过如何读取.ini配置文件,所以此部分,将发送邮件的一些要素放在了配置文件中,配置文件如下:
对应读取配置文件脚本为:(readconfig.py部分)
import osimport configparser# configcur_path = os.path.dirname(os.path.relpath(__file__))configpath = os.path.join(cur_path,'config.ini')conf = configparser.configparser()conf.read(configpath)def get_smtpserver(smtpserver): smtp_server = conf.get('email',smtpserver) return smtp_server# ......
三、邮件部分构建mimemultipart()邮件根容器对象后,需要借助根容器来定义邮件的各个要素,比如邮件主题subject、发送人from、接收人to、邮件正文body、邮件附件等。
如何给邮件定主题、收发人呢?# 构建根容器msg = mimemultipart()# 邮件主题、发送人、收件人、内容,此部分可以来自配置文件,也可以直接填入msg['subject'] = self.mail_subject # u'自动化测试报告'msg['from'] = self.mail_sendermsg['to'] = self.mail_pwd
如何定义邮件正文body部分呢?# 邮件正文部分body,1、可以用html自己自定义body内容;2、读取其他文件的内容为body# body = 您好,<p>这里是使用python登录邮箱,并发送附件的测试<\p>with open(reportfile,'r',encoding='utf-8') as f: body = f.read()msg.attach(mimetext(_text=body, _subtype='html', _charset='utf-8')) # _charset 是指content_type的类型
如何给邮件添加附件呢?# 添加附件attachment = mimetext(_text=open(reportfile, 'rb').read(), _subtype='base64',_charset= 'utf-8')attachment['content-type'] = 'application/octet-stream'attachment['content-disposition'] = 'attachment;filename = result.html'msg.attach(attachment)
如何发送?发送四部曲:取得服务器连接、再登录邮箱、发送邮件、退出。
大致如下啦:
try: smtp = smtplib.smtp_ssl(host=self.mail_smtpserver, port=self.mail_port) # 继承自smtpexcept: smtp = smtplib.smtp() smtp.connect(self.mail_smtpserver, self.mail_port)# smtp.set_debuglevel(1)# 创建安全连接,加密smtpsmtp.starttls() # puts the connection to the smtp server into tls mode.# 用户名和密码smtp.login(user=self.mail_sender, password=self.mail_pwd)# 函数:sendmail(self, from_addr, to_addrs, msg, mail_options=[],rcpt_options=[]):smtp.sendmail(self.mail_sender, self.mail_receiverlist, msg.as_string())smtp.quit()
在里面添加了一句smtp.starttls()。这一句是用来加密smtp会话,保证邮件安全发送不被窃听的。
在创建完smtp对象后,立刻调用starttls()方法即可。
其实整个下来邮件发送模块也就完成了。
四、问题在这个过程中有遇见几个问题,也贴上来跟大家一起分享一下。
抛错535
抛错:smtplib.smtpauthenticationerror: (535, b'error: xc7xebxcaxb9xd3xc3xcaxdaxc8xa8xc2xebxb5xc7xc2xbcxa1xa3xcfxeaxc7xe9xc7xebxbfxb4: http://service.mail.qq.com/cg...')
解决办法:点击最后的链接,其实是因为授权码问题
替换授权码后继续报错,535
解决办法:替换端口。因为qq邮箱ssl协议端口有两个:465/587。
报错:smtplib.smtpauthenticationerror: (530, b'must issue a starttls command first.')
解决方法:在login()之前,添加一句:smtp.starttls()
五、代码all下面贴上整个文件,这个文件是依赖于其他文件的的,所以仅供参考,但是方法是一样的。
import smtplibfrom email.mime.text import mimetextfrom email.mime.multipart import mimemultipartfrom email.mime.base import mimebaseclass sendemail(object): ''' 发送邮件模块封装,属性均从config.ini文件获得 ''' def __init__(self, smtpserver, mailport, mailsender, mailpwd, mailtolist, mailsubject): self.mail_smtpserver = smtpserver self.mail_port = mailport self.mail_sender = mailsender self.mail_pwd = mailpwd # 接收邮件列表 self.mail_receiverlist = mailtolist self.mail_subject = mailsubject # self.mail_content = mailcontent def sendfile(self, reportfile): ''' 发送各种类型的附件 ''' # 构建根容器 msg = mimemultipart() # 邮件正文部分body,1、可以用html自己自定义body内容;2、读取其他文件的内容为body # body = 您好,<p>这里是使用python登录邮箱,并发送附件的测试<\p> with open(reportfile,'r',encoding='utf-8') as f: body = f.read() # _charset 是指content_type的类型 msg.attach(mimetext(_text=body, _subtype='html', _charset='utf-8')) # 邮件主题、发送人、收件人、内容 msg['subject'] = self.mail_subject # u'自动化测试报告' msg['from'] = self.mail_sender msg['to'] = self.mail_pwd # 添加附件 attachment = mimetext(_text=open(reportfile, 'rb').read(), _subtype='base64',_charset= 'utf-8') attachment['content-type'] = 'application/octet-stream' attachment['content-disposition'] = 'attachment;filename = result.html' msg.attach(attachment) try: smtp = smtplib.smtp_ssl(host=self.mail_smtpserver, port=self.mail_port) # 继承自smtp except: smtp = smtplib.smtp() smtp.connect(self.mail_smtpserver, self.mail_port) # smtp.set_debuglevel(1) # 创建安全连接,加密smtp smtp.starttls() # puts the connection to the smtp server into tls mode. # 用户名和密码 smtp.login(user=self.mail_sender, password=self.mail_pwd) # 函数:sendmail(self, from_addr, to_addrs, msg, mail_options=[],rcpt_options=[]): smtp.sendmail(self.mail_sender, self.mail_receiverlist, msg.as_string()) smtp.quit()# 调试代码if __name__ == __main__: mail_smtpserver = 'smtp.qq.com' mail_port = 587 mail_sender = '@qq.com' mail_pwd = '' mail_receiverlist = ['@qq.com', '@163.com'] mail_subject = u'自动化测试报告' s = sendemail(mail_smtpserver, mail_port, mail_sender, mail_pwd, mail_receiverlist, mail_subject) s.sendfile('f:\python_project\pythonlearnning_2018\send_email\sendemail_test.html.tar.gz') print('--- test end --- ')
以上就是python smtp发送邮件的详细介绍(附代码)的详细内容。