【Python】python发邮件详解,smtplib和email模块详解
在介绍具体的实现python发邮件的具体操作之前,我觉得有必要介绍下SMTP,更有助于理解python发邮件的实现原理。SMTP协议属于TCP/IP协议簇,即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式,python实现发邮件也是基于此基础上进行封装的。
1.python发邮件所需要的基础包
python发送邮件需要用到python自带的两个模块,smtplib和email。直接import导入,无需下载。
python的smtplib提供了一种很方便的途径发送电子邮件,它对smtp协议进行了简单的封装。
2.smtplib的用法
smtplib用法相对来说很简单,就是分为两步。
创建SMTP的操作对象并连接smtp目标服务器,可以是163、QQ等
根据自己的账号登录目标服务器(自己的邮箱地址和邮箱授权码)
调用对象中的方法,发送邮件到目标地址
python与smtp服务器之间的具体交互的通用代码:
import smtplib server = smtplib.SMTP(mailserver, port) # 发件人邮箱中的SMTP服务器,端口是25 server.login(sender, passwd) # 发件人邮箱账号、邮箱授权码 # msg.as_string()中as_string()是将msg(MIMEText或MIMEMultipart对象)变为str。 server.sendmail(sender, receive, msg.as_string()) server.quit()
具体的python连接目标服务器的代码如下:注:本文章用的是qq的smtp服务器。
常用邮箱的smtp服务器地址:
新浪邮箱:smtp.sina.com,搜狐邮箱:smtp.sohu.com,qq邮箱:smtp.qq.com
sender_maile='80617252@qq.com' # 发送方的邮箱地址 sender_pass = 'lsjdfsljdfk' # 邮箱提供的授权码,可在第三方登录,我这个是随便打的。 sftp_obj =smtplib.SMTP('smtp.qq.com', 25) sftp_obj.login(sender_mail, sender_pass) #三个参数分别是:发件人邮箱账号,收件人邮箱账号,发送的邮件体 sftp_obj.sendmail(sender_mail, receiver_mail, msg_root.as_string()) sftp_obj.quit()
3.email模块的详细理解和使用
email模块下的mime模块下有常用的三个模块,三个模块中有三个大类。其实就是下边这三个了,说的很绕,下边为导入方式,一目了然。
from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart
简单说下他们的关系,如果构造一个MIMEText对象,就表示一个文本邮件对象,如果构造一个MIMEImage对象,就表示一个作为附件的图片对象,要把多个对象组合起来,就用MIMEMultipart对象,他代表的是整个邮件。这样说应该还不是很清晰,下边就分开来说,最后会总的总结,在最后边就是完整的代码(可以发送一切内容的代码)。
A.MIMEText对象中有三个需要我们设置的参数,一个是正文内容,一个是正文内容的类型,例如:”text/plain”和”text/html”,一个是正文内容的编码。
构造普通文本:
text_info = 'hello world ' text_sub = MIMEText(text_info,'plain', 'utf-8')
构造超文本:
url = "https://blog.csdn.net/chinesepython" html_info = """ <p>点击以下链接,你会去向一个更大的世界</p> <p><a href="%s">click me</a></p> <p>i am very glasses for you</p> """ % url html_sub = MIMEText(html_info, 'html', 'utf-8') # 如果不加下边这行代码的话,上边的文本是不会正常显示的,会把超文本的内容当做文本显示 html_sub["Content-Disposition"] = 'attachment; filename="csdn.html"'
构造base64数据流,用于发送文件的时候使用,构造附件代码:
txt_file = open(r'D:\python_files\files\hello_world.txt', 'rb').read() txt = MIMEText(txt_file, 'base64', 'utf-8') txt["Content-Type"] = 'application/octet-stream' # 命名发送的附件 txt.add_header('Content-Disposition', 'attachment', filename='hello_world.txt')
B.MIMEImage对象中只需要把读取的文件传入就行
构造图片:
image_file = open(r'D:\python_files\images\test.png', 'rb').read() image = MIMEImage(image_file) image.add_header('Content-ID', '<image1>') # 命名发送的图片 image["Content-Disposition"] = 'attachment; filename="red_people.png"'
C.MIMEMultipart对象创建的类型有三种,此模块主要是通过attach方法把上边构造的内容传入到邮件的整体内容中。
邮件类型为”multipart/alternative”的邮件正文中包括纯文本正文(text/plain)和超文本正文(text/html)。
邮件类型为”multipart/related”的邮件正文中包括图片,声音等内嵌资源。
邮件类型为”multipart/mixed”的邮件包含附件,图片,文本等都可以添加,所以发的内容多的话一般是用这个的,选择mixed类型,什么内容都可以发。
3.邮件头添加内容
直接上示例代码:
from email.mime.multipart import MIMEMultipart msg_root = MIMEMultipart('mixed') # 发件人 msg_root['From'] = 'aaa@qq.com<aaa@qq.com>' # 收件人 msg_root['To'] = '666666@qq.com' # 邮件主题 subject = 'python sendemail test successful' msg_root['subject'] = Header(subject, 'utf-8')
4.特别的用法说明:
注:以下的msg_root为:
msg_root = MIMEMultipart(‘mixed’)
msg_root.as_string()是将msg_root对象变为str。
msg_root.attach(MIMEText或者MIMEImage对象),因为MIMEMultipart对象代表邮件本身,其他连个是代表邮件正文,所以这个方法还是很强大的,把其他的构造内容添加到MIMEMultipart对象中就可以把文本,html,附件等一起发送了。
5.发送各种内容的具体代码实现:
所有代码合到一块,发送文本,html,图片,txt内容,用的时候你可以把需要的部分摘出来,也就是把没有加入到msg_root的对象拿出来,直接通过下边命令发送,例如只发送文本。
sftp_obj.sendmail(sender_mail, receiver_mail, text_sub.as_string())。 import smtplib from email.header import Header from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart def send_email_by_qq(to): sender_mail = '80617252@qq.com' sender_pass = 'aljflsjdf'#同样是乱打的 # 设置总的邮件体对象,对象类型为mixed msg_root = MIMEMultipart('mixed') # 邮件添加的头尾信息等 msg_root['From'] = '80617252@qq.com<80617252@qq.com>' msg_root['To'] = to # 邮件的主题,显示在接收邮件的预览页面 subject = 'python sendemail test successful' msg_root['subject'] = Header(subject, 'utf-8') # 构造文本内容 text_info = 'hello world' text_sub = MIMEText(text_info, 'plain', 'utf-8') msg_root.attach(text_sub) # 构造超文本 url = "https://blog.csdn.net/chinesepython" html_info = """ <p>点击以下链接,你会去向一个更大的世界</p> <p><a href="%s">click me</a></p> <p>i am very galsses for you</p> """% url html_sub = MIMEText(html_info, 'html', 'utf-8') # 如果不加下边这行代码的话,上边的文本是不会正常显示的,会把超文本的内容当做文本显示 html_sub["Content-Disposition"] = 'attachment; filename="csdn.html"' # 把构造的内容写到邮件体中 msg_root.attach(html_sub) # 构造图片 image_file = open(r'D:\python_files\images\test.png', 'rb').read() image = MIMEImage(image_file) image.add_header('Content-ID', '<image1>') # 如果不加下边这行代码的话,会在收件方方面显示乱码的bin文件,下载之后也不能正常打开 image["Content-Disposition"] = 'attachment; filename="red_people.png"' msg_root.attach(image) # 构造附件 txt_file = open(r'D:\python_files\files\hello_world.txt', 'rb').read() txt = MIMEText(txt_file, 'base64', 'utf-8') txt["Content-Type"] = 'application/octet-stream' #以下代码可以重命名附件为hello_world.txt txt.add_header('Content-Disposition', 'attachment', filename='hello_world.txt') msg_root.attach(txt) try: sftp_obj =smtplib.SMTP('smtp.qq.com', 25) sftp_obj.login(sender_mail, sender_pass) sftp_obj.sendmail(sender_mail, to, msg_root.as_string()) sftp_obj.quit() print('sendemail successful!') except Exception as e: print('sendemail failed next is the reason') print(e) if __name__ == '__main__': # 可以是一个列表,支持多个邮件地址同时发送,测试改成自己的邮箱地址 to = '666666@qq.com' send_email_by_qq(to)
6.总结
为了让不是很理解发邮件的朋友能更好的理解,在这里是把所有的参数都写死了,比如说发送文件的具体内容,在真正开发使用过程中,可以把具体的内容通过预留出来参数去传入之后发送你想要发送的内容。
发邮件功能还是很实用的,在真正的开发中或者大多数场合都能用到,比如说项目中一个重要的模块如果出问题了,你需要第一时间知道,就可以加入这个功能,把项目出问题报的具体内容发到你的邮箱,也可以第一时间想下处理的对策。
下面以我通过此程序发送的邮件内容的截图做结尾吧。
---------------------
摘自:https://blog.csdn.net/chinesepython/article/details/82465947

赠人玫瑰
手留余香
我们曾如此渴望命运的波澜,到最后才发现:人生最曼妙的风景,竟是内心的淡定与从容……我们曾如此期盼外界的认可,到最后才知道:世界是自己的,与他人毫无关系!-杨绛先生
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2014-06-25 【原】Ubuntu下使用teamviewer