0

0

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

不言

不言

发布时间:2018-10-09 15:39:31

|

3240人浏览过

|

来源于segmentfault思否

转载

本篇文章给大家带来的内容是关于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配置文件,所以此部分,将发送邮件的一些要素放在了配置文件中,配置文件如下:

立即学习Python免费学习笔记(深入)”;

576842298-5ba23ef2a642d_articlex.png

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

爱图表
爱图表

AI驱动的智能化图表创作平台

下载
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登录邮箱,并发送附件的测试<\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)  # 继承自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登录邮箱,并发送附件的测试<\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速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
虚拟号码教程汇总
虚拟号码教程汇总

本专题整合了虚拟号码接收验证码相关教程,阅读下面的文章了解更多详细操作。

29

2025.12.25

错误代码dns_probe_possible
错误代码dns_probe_possible

本专题整合了电脑无法打开网页显示错误代码dns_probe_possible解决方法,阅读专题下面的文章了解更多处理方案。

20

2025.12.25

网页undefined啥意思
网页undefined啥意思

本专题整合了undefined相关内容,阅读下面的文章了解更多详细内容。后续继续更新。

37

2025.12.25

word转换成ppt教程大全
word转换成ppt教程大全

本专题整合了word转换成ppt教程,阅读专题下面的文章了解更多详细操作。

6

2025.12.25

msvcp140.dll丢失相关教程
msvcp140.dll丢失相关教程

本专题整合了msvcp140.dll丢失相关解决方法,阅读专题下面的文章了解更多详细操作。

2

2025.12.25

笔记本电脑卡反应很慢处理方法汇总
笔记本电脑卡反应很慢处理方法汇总

本专题整合了笔记本电脑卡反应慢解决方法,阅读专题下面的文章了解更多详细内容。

6

2025.12.25

微信调黑色模式教程
微信调黑色模式教程

本专题整合了微信调黑色模式教程,阅读下面的文章了解更多详细内容。

5

2025.12.25

ps入门教程
ps入门教程

本专题整合了ps相关教程,阅读下面的文章了解更多详细内容。

4

2025.12.25

苹果官网入口直接访问
苹果官网入口直接访问

苹果官网直接访问入口是https://www.apple.com/cn/,该页面具备0.8秒首屏渲染、HTTP/3与Brotli加速、WebP+AVIF双格式图片、免登录浏览全参数等特性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

218

2025.12.24

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 2.4万人学习

SciPy 教程
SciPy 教程

共10课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号