答案:Python发送邮件需使用smtplib和email模块,通过SMTP服务器认证连接并构造邮件内容。首先配置发件人邮箱、授权码、收件人及服务器信息,利用MIMEText创建纯文本邮件,MIMEMultipart构建多部分邮件以添加附件或HTML内容,发送时启用TLS或SSL加密,并妥善处理异常。常见问题多为授权码错误、服务器端口配置不当或邮箱服务未开启,需逐一排查。

用Python发送邮件,核心在于利用其内置的
smtplib
smtplib
解决方案 发送一封最基础的纯文本邮件,我们需要几个关键步骤。这通常是我开始一个新邮件自动化项目时的起点,简单直接,能快速验证连接和认证是否成功。
首先,导入必要的模块:
smtplib
email.mime.text.MIMEText
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 邮件配置
sender_email = 'your_email@example.com' # 发件人邮箱
sender_password = 'your_app_password' # 发件人邮箱的授权码(或密码,但不推荐直接使用主密码)
receiver_email = 'recipient@example.com' # 收件人邮箱
smtp_server = 'smtp.example.com' # SMTP服务器地址,例如:smtp.gmail.com, smtp.qq.com
smtp_port = 587 # SMTP服务器端口,SSL通常是465,TLS通常是587
# 邮件内容
subject = 'Python发送测试邮件'
body = '你好!这是一封由Python脚本发送的测试邮件。'
# 构建MIMEText对象
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = Header(f'发件人名称 <{sender_email}>', 'utf-8')
msg['To'] = Header(f'收件人名称 <{receiver_email}>', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
try:
# 连接SMTP服务器
# 对于TLS加密,使用starttls()
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # 启动TLS加密
# 登录邮箱
server.login(sender_email, sender_password)
# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())
print('邮件发送成功!')
except smtplib.SMTPException as e:
print(f'邮件发送失败: {e}')
except Exception as e:
print(f'发生未知错误: {e}')
finally:
if 'server' in locals() and server:
server.quit() # 关闭连接这里需要特别注意的是
sender_password
Python发送带附件的邮件怎么实现? 在实际应用中,纯文本邮件往往不够用,我们经常需要发送带有文件附件的邮件。这比纯文本邮件稍微复杂一点,但
MIMEMultipart
要发送带附件的邮件,我们需要使用
email.mime.multipart.MIMEMultipart
立即学习“Python免费学习笔记(深入)”;
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.header import Header
import os
sender_email = 'your_email@example.com'
sender_password = 'your_app_password'
receiver_email = 'recipient@example.com'
smtp_server = 'smtp.example.com'
smtp_port = 587
subject = '带附件的Python测试邮件'
body = '你好!这是一封带附件的Python测试邮件。请查收附件。'
attachment_path = 'path/to/your/file.pdf' # 附件的完整路径
# 创建MIMEMultipart对象,用于组合邮件正文和附件
msg = MIMEMultipart()
msg['From'] = Header(f'发件人名称 <{sender_email}>', 'utf-8')
msg['To'] = Header(f'收件人名称 <{receiver_email}>', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
# 添加邮件正文
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# 添加附件
if os.path.exists(attachment_path):
try:
with open(attachment_path, 'rb') as f:
# 创建MIMEBase对象,用于表示附件
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
# 对附件进行Base64编码
encoders.encode_base64(part)
# 设置附件的文件名,确保中文文件名能正确显示
file_name = os.path.basename(attachment_path)
part.add_header('Content-Disposition', 'attachment', filename=(Header(file_name, 'utf-8').encode()))
msg.attach(part)
print(f"附件 '{file_name}' 添加成功。")
except FileNotFoundError:
print(f"错误:附件文件 '{attachment_path}' 未找到。")
except Exception as e:
print(f"添加附件时发生错误: {e}")
else:
print(f"警告:附件文件 '{attachment_path}' 不存在,邮件将不包含此附件。")
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print('带附件的邮件发送成功!')
except smtplib.SMTPException as e:
print(f'邮件发送失败: {e}')
except Exception as e:
print(f'发生未知错误: {e}')
finally:
if 'server' in locals() and server:
server.quit()这里需要注意
MIMEBase('application', 'octet-stream')encoders.encode_base64(part)
Content-Disposition
Header(file_name, 'utf-8').encode()
如何用Python发送HTML格式的邮件? 现代邮件客户端对HTML格式的支持非常普遍,发送HTML邮件能让你的内容更具吸引力,可以包含图片、链接、排版等。我个人在发送报告、通知或营销邮件时,几乎总是倾向于使用HTML格式。
发送HTML邮件与发送纯文本邮件类似,只是在创建
MIMEText
_subtype
'html'
MIMEMultipart
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
sender_email = 'your_email@example.com'
sender_password = 'your_app_password'
receiver_email = 'recipient@example.com'
smtp_server = 'smtp.example.com'
smtp_port = 587
subject = 'Python发送HTML格式邮件'
# HTML邮件内容
html_body = """\
<html>
<head></head>
<body>
<p>你好!</p>
<p>这是一封由Python脚本发送的<b>HTML格式</b>测试邮件。</p>
<p>你可以点击这里访问我的<a href="https://example.com">网站</a>。</p>
<img src="https://via.placeholder.com/150" alt="Placeholder Image">
<p>祝好!</p>
</body>
</html>
"""
# 纯文本备用内容
text_body = "你好!这是一封由Python脚本发送的HTML格式测试邮件。\n请访问我的网站:https://example.com"
# 创建MIMEMultipart对象,用于组合纯文本和HTML版本
msg = MIMEMultipart('alternative') # 'alternative'表示这些部分是同一内容的替代表示
msg['From'] = Header(f'发件人名称 <{sender_email}>', 'utf-8')
msg['To'] = Header(f'收件人名称 <{receiver_email}>', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
# 添加纯文本部分
msg.attach(MIMEText(text_body, 'plain', 'utf-8'))
# 添加HTML部分
msg.attach(MIMEText(html_body, 'html', 'utf-8'))
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(sender_email, sender_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print('HTML格式邮件发送成功!')
except smtplib.SMTPException as e:
print(f'邮件发送失败: {e}')
except Exception as e:
print(f'发生未知错误: {e}')
finally:
if 'server' in locals() and server:
server.quit()这里关键是
MIMEMultipart('alternative')<img>
cid:
email.mime.image.MIMEImage
Content-ID
Python发送邮件,遇到身份验证失败怎么办? 身份验证失败是我在自动化邮件脚本开发中最常遇到的问题之一。它往往不是代码逻辑错误,而是配置或安全策略上的问题。遇到这类问题,首先不要慌,一步步排查通常都能解决。
sender_email
sender_password
smtp_server
smtp_port
smtp.gmail.com
smtp.qq.com
smtp.office365.com
smtp.163.com
server = smtplib.SMTP(smtp_server, smtp_port)
smtplib.SMTP_SSL(smtp_server, smtp_port)
server.starttls()
smtplib.SMTP_SSL()
starttls()
smtplib.SMTPAuthenticationError
smtplib.SMTPException
我的建议是,遇到认证问题,先去你的邮箱服务商官网查找其SMTP配置文档,然后对照你的代码和账户设置逐一检查。通常,问题都出在授权码或SMTP服务器/端口的配置上。
以上就是如何用Python发送邮件?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号