栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python SMTP发送邮件的详细介绍(附代码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python SMTP发送邮件的详细介绍(附代码)

本篇文章给大家带来的内容是关于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 smtplib
1、构造MIMEMultipart对象作为根容器
2、构造MIMEText对象作为邮件显示内容并附加到根容器
    a、读入文件内容并格式化
    b、设置附件头
3、设置根容器属性
4、得到格式化后的完整文本
5、用smtp发送邮件
6、封装成sendEmail类。
二、邮件发送要素

同时想想我们要发送邮件的几个要素:

1、服务器。以QQ邮箱举例,则为smtp.qq.com
2、端口号。有465和587,请使用587
3、发送者。
4、密码。密码总不能直接写在文件里吧?哈哈,这里需要使用qq邮箱获取授权码。
5、收件人。(可能还不止一个)
6、发送邮件的主题subject。
7、邮件文本内容。
8、附件。

因为之前写过如何读取.ini配置文件,所以此部分,将发送邮件的一些要素放在了配置文件中,配置文件如下:

对应读取配置文件脚本为:(readConfig.py部分)

import os
import configparser

# config
cur_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_sender
msg['to'] = self.mail_pwd
如何定义邮件正文body部分呢?
# 邮件正文部分body,1、可以用HTML自己自定义body内容;2、读取其他文件的内容为body
# body = "您好,

这里是使用Python登录邮箱,并发送附件的测试

" 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)  # 继承自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()

在里面添加了一句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 smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase

class 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 = "您好,

这里是使用Python登录邮箱,并发送附件的测试

" 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_projectPythonLearnning_2018send_emailsendEmail_Test.html.tar.gz') print('--- test end --- ')

以上就是python SMTP发送邮件的详细介绍(附代码)的详细内容,更多请关注考高分网其它

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/805874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号