news 2026/7/15 1:14:29

Python - 发送电子邮件

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Python - 发送电子邮件

用Python发送电子邮件

你可以用 Python 发送邮件,使用多个库,但最常见的是smtplibemail

Python 中的“smtplib”模块定义了一个 SMTP 客户端会话对象,可用于向任何带有 SMTP 或 ESMTP 监听器守护进程的互联网机器发送邮件。电子邮件“包”是一个用于管理电子邮件的库,包括MIME和其他基于RFC 2822的消息文档。

处理和传递电子邮件的应用程序称为“邮件服务器”。简单邮件传输协议(SMTP)是一种协议,用于在邮件服务器之间发送电子邮件和路由邮件。它是电子邮件传输的互联网标准。

Python smptlib.SMTP() 功能

Python smptlib.SMTP() 函数用于创建 SMTP 客户端会话对象,建立与 SMTP 服务器的连接。这种连接允许你通过服务器发送邮件。

搭建SMTP服务器

在发送邮件之前,你需要搭建一个SMTP服务器。常见的SMTP服务器包括Gmail、Yahoo或其他邮件服务提供商提供的服务器。

创建 SMTP 对象

发送电子邮件时,你需要通过以下函数获得SMTP类的对象——

import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

以下是参数的详细情况 −

  • host− 这是运行你 SMTP 服务器的主机。你可以指定主机的IP地址或域名,比如tutorialspoint.com。这是一个可选的论点。

  • port− 如果你提供主机参数,则需要指定一个端口,其中SMTP服务器正在监听。通常这个端口是25。

  • local_hostname− 如果你的SMTP服务器运行在本地机器上,那么你可以选择只用localhost作为选项。

示例

以下脚本连接到端口25的“smtp.example.com”SMTP服务器,可选地识别并保护连接,登录(如有需要),发送邮件,然后退出会话−

import smtplib # Create an SMTP object and establish a connection to the SMTP server smtpObj = smtplib.SMTP('smtp.example.com', 25) # Identify yourself to an ESMTP server using EHLO smtpObj.ehlo() # Secure the SMTP connection smtpObj.starttls() # Login to the server (if required) smtpObj.login('username', 'password') # Send an email from_address = 'your_email@example.com' to_address = 'recipient@example.com' message = """\ Subject: Test Email This is a test email message. """ smtpObj.sendmail(from_address, to_address, message) # Quit the SMTP session smtpObj.quit()

Python smtpd 模块

Pythonsmtpd模块用于创建和管理一个简单的邮件传输协议(SMTP)服务器。该模块允许您搭建一个SMTP服务器,能够接收和处理来电邮件,因此在测试和调试应用内的电子邮件功能时非常有价值。

搭建 SMTP 调试服务器

smtpd 模块预装了 Python,并包含本地 SMTP 调试服务器。该服务器适合测试电子邮件功能,而无需实际发送邮件到指定地址;相反,它会将邮件内容打印到控制台。

运行该本地服务器消除了处理消息加密或使用凭证登录邮件服务器的需求。

启动 SMTP 调试服务器

您可以使用命令提示符或终端中的以下命令启动本地 SMTP 调试服务器 −

python -m smtpd -c DebuggingServer -n localhost:1025

示例

以下示例演示如何利用 smtplib 功能与本地 SMTP 调试服务器一起发送假邮件 −

import smtplib def prompt(prompt): return input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() print("Enter message, end with ^D (Unix) or ^Z (Windows):") # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) while True: try: line = input() except EOFError: break if not line: break msg = msg + line print("Message length is", len(msg)) server = smtplib.SMTP('localhost', 1025) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit()

在此例中 −

  • From− 你输入发送者的电子邮件地址(fromaddr)。

  • To− 你输入收件人的电子邮件地址(toaddrs),可以是多个用空格分隔的地址。

  • Message− 你输入消息内容,结尾为 ^D(Unix)或 ^Z(Windows)。

sendmail() 方法中的“smtplib”会将邮件发送到运行于“localhost”(1025端口)的本地 SMTP 调试服务器,使用指定的发送人、收件人和消息内容。

输出

当你运行程序时,控制台会输出程序和SMTP服务器之间的通信。与此同时,运行SMTPD服务器的终端会显示收到的邮件内容,帮助你调试和验证邮件发送过程。

python example.py From: abc@xyz.com To: xyz@abc.com Enter message, end with ^D (Unix) or ^Z (Windows): Hello World ^Z

控制台反映的日志如下 −

From: abc@xyz.com reply: retcode (250); Msg: b'OK' send: 'rcpt TO:<xyz@abc.com>\r\n' reply: b'250 OK\r\n' reply: retcode (250); Msg: b'OK' send: 'data\r\n' reply: b'354 End data with <CR><LF>.<CR><LF>\r\n' reply: retcode (354); Msg: b'End data with <CR><LF>.<CR><LF>' data: (354, b'End data with <CR><LF>.<CR><LF>') send: b'From: abc@xyz.com\r\nTo: xyz@abc.com\r\n\r\nHello World\r\n.\r\n' reply: b'250 OK\r\n' reply: retcode (250); Msg: b'OK' data: (250, b'OK') send: 'quit\r\n' reply: b'221 Bye\r\n' reply: retcode (221); Msg: b'Bye'

SMTPD服务器运行的终端显示该输出

---------- MESSAGE FOLLOWS ---------- b'From: abc@xyz.com' b'To: xyz@abc.com' b'X-Peer: ::1' b'' b'Hello World' ------------ END MESSAGE ------------

使用 Python 发送 HTML 邮件

要用 Python 发送 HTML 邮件,你可以使用smtplib库连接到 SMTP 服务器,使用email.mime模块来合理构建和格式化你的邮件内容。

构建HTML邮件消息

发送HTML邮件时,你需要指定特定的头部并相应结构化消息内容,以确保收件人的邮件客户端识别并呈现为HTML。

示例

以下是在 Python 中以电子邮件形式发送 HTML 内容的示例 −

import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Email content sender = 'from@fromdomain.com' receivers = ['to@todomain.com'] # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['From'] = 'From Person <from@fromdomain.com>' msg['To'] = 'To Person <to@todomain.com>' msg['Subject'] = 'SMTP HTML e-mail test' # HTML message content html = """\ <html> <head></head> <body> <p>This is an e-mail message to be sent in <b>HTML format</b></p> <p><b>This is HTML message.</b></p> <h1>This is headline.</h1> </body> </html> """ # Attach HTML content to the email part2 = MIMEText(html, 'html') msg.attach(part2) # Connect to SMTP server and send email try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, msg.as_string()) print("Successfully sent email") except smtplib.SMTPException as e: print(f"Error: unable to send email. Error message: {str(e)}")

以电子邮件发送附件

要在 Python 中发送电子邮件附件,您可以使用smtplib库连接到 SMTP 服务器,使用email.mime模块来构建和格式化您的邮件内容,包括附件。

构建带有附件的电子邮件

发送带有附件的邮件时,你需要使用MIME(多用途互联网邮件扩展)正确格式化邮件。这需要将Content-Type头设置为multipart/mixed,表示邮件包含文本和附件。邮件的每个部分(文本和附件)都被边界分隔开。

示例

以下是示例,发送带有文件/tmp/test.txt作为附件的电子邮件 −

import smtplib import base64 filename = "/tmp/test.txt" # Read a file and encode it into base64 format fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent) # base64 sender = 'webmaster@tutorialpoint.com' reciever = 'amrood.admin@gmail.com' marker = "AUNIQUEMARKER" body =""" This is a test email to send an attachment. """ # Define the main headers. part1 = """From: From Person <me@fromdomain.net> To: To Person <amrood.admin@gmail.com> Subject: Sending Attachment MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) # Define the message action part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit %s --%s """ % (body,marker) # Define the attachment section part3 = """Content-Type: multipart/mixed; name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename=%s %s --%s-- """ %(filename, filename, encodedcontent, marker) message = part1 + part2 + part3 try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, reciever, message) print "Successfully sent email" except Exception: print "Error: unable to send email"

使用 Gmail 的 SMTP 服务器发送电子邮件

要用 Gmail 的 Python SMTP 服务器发送邮件,你需要在 “587” 端口smtp.gmail.com设置连接,使用“TLS”加密,使用 Gmail 凭证进行认证,使用 Python 的 smtplib 和 email.mime 库构建邮件,然后使用 sendmail() 方法发送。最后,用 quit() 关闭 SMTP 连接。

示例

以下是一个示例脚本,演示如何使用Gmail的SMTP服务器发送电子邮件 −

import smtplib # Email content content = "Hello World" # Set up SMTP connection to Gmail's SMTP server mail = smtplib.SMTP('smtp.gmail.com', 587) # Identify yourself to the SMTP server mail.ehlo() # Start TLS encryption for the connection mail.starttls() # Gmail account credentials sender = 'your_email@gmail.com' password = 'your_password' # Login to Gmail's SMTP server mail.login(sender, password) # Email details recipient = 'recipient_email@example.com' subject = 'Test Email' # Construct email message with headers header = f'To: {recipient}\nFrom: {sender}\nSubject: {subject}\n' content = header + content # Send email mail.sendmail(sender, recipient, content) # Close SMTP connection mail.quit()

在运行上述脚本之前,发件人的 Gmail 账户必须配置为允许访问“更少” 安全应用。点击以下链接。

https://myaccount.google.com/lesssecureapps 将显示的切换按钮设置为开启。

如果一切顺利,执行上述脚本。消息应被送达到收件人的收件箱。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/14 23:00:57

Langchain-Chatchat结合GPU加速推理,实现高性能问答服务

Langchain-Chatchat 结合 GPU 加速推理&#xff0c;打造高性能本地问答系统 在企业知识管理日益复杂的今天&#xff0c;如何让员工快速获取分散在成百上千份文档中的关键信息&#xff0c;已成为组织效率提升的瓶颈。一个常见的场景是&#xff1a;新员工想了解公司的差旅报销标准…

作者头像 李华
网站建设 2026/7/11 22:01:44

研究生必备:9款AI论文神器,真实文献交叉引用,一键生成文献综述

如果你是正在熬夜赶Deadline的毕业生&#xff0c;面对堆积如山的文献资料却无从下笔&#xff1b;或是面临延毕压力&#xff0c;被导师催稿催得焦头烂额的研究生&#xff1b;又或是没钱去支付高昂知网查重费用的大学生&#xff0c;别担心&#xff0c;这篇文章就是为你量身打造的…

作者头像 李华
网站建设 2026/7/14 10:27:02

2025中国iPaaS市场份额独立第一测评小白快速上手方法与步骤

《2025中国iPaaS行业发展白皮书》明确指出&#xff0c;企业集成平台优势明显已成为数智化转型的核心支撑。《2025中国iPaaS产品权威测评》通过对20主流平台的技术能力、用户体验、市场覆盖等维度评估&#xff0c;结合《2025中国iPaaS产品排行榜》数据&#xff0c;连趣云iPaaS平…

作者头像 李华
网站建设 2026/7/12 2:29:44

测试诚信原则:数字时代质量防线的基石与践行路径

测试诚信的时代呼唤 在数字化浪潮席卷全球的2025年&#xff0c;软件已深入社会各个角落&#xff0c;从医疗设备到金融系统&#xff0c;从智能家居到自动驾驶&#xff0c;其质量直接关乎人类安全与效率。作为软件质量的“守门人”&#xff0c;测试从业者的责任空前重大。然而&a…

作者头像 李华
网站建设 2026/7/11 11:49:02

实测 GPT-5.2 与 Gemini-3:我用 AI 重构了 3000 行核心代码,结果令人沉默

别再手写前端了&#xff1a;Banana Pro (Gemini-3-Image) 视觉模型实战评测&#xff0c;草图秒变代码作为一名写了十年代码的老程序员我一直坚信一个观点代码质量是衡量工程师水平的唯一标准直到昨天我花了两天两夜优化了一个复杂的并发算法模块沾沾自喜地准备提交结果我手欠试…

作者头像 李华
网站建设 2026/7/14 3:56:31

代码之恋(第十五篇:分布式心跳与网络延迟)

南国的早晨&#xff0c;李磊站在新租的公寓窗前&#xff0c;看着陌生的城市。来小渔村一周&#xff0c;升职带来的兴奋已褪去&#xff0c;剩下的是对江城的思念。他打开电脑&#xff0c;屏幕上显示着与艾丽的视频通话窗口——这是他们每晚的“同步时间”。// Collaboration_v3.…

作者头像 李华