使用 Python smtplib 和 email 库发送一封带有附件的邮件。
以下是使用Python发送带有附件的邮件的完整程序。该程序使用SMTP协议,支持主流邮箱(如163、QQ、Gmail等),并包含详细的注释说明:
# -*- coding: utf-8 -*-
""" send_email_1.py 发送一封带有附件的邮件 """
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os
def send_email_with_attachment(
smtp_server: str,
smtp_port: int,
sender_email: str,
password: str,
receiver_email: str,
subject: str,
body: str,
attachment_path: str,
use_tls: bool = True
):
"""
发送带有附件的电子邮件
参数:
smtp_server: SMTP服务器地址 (如: smtp.163.com)
smtp_port: SMTP服务器端口 (如: 465或587)
sender_email: 发件人邮箱地址
password: 发件人邮箱密码/授权码
receiver_email: 收件人邮箱地址
subject: 邮件主题
body: 邮件正文 (支持HTML)
attachment_path: 附件文件路径
use_tls: 是否使用TLS加密 (SSL加密自动根据端口判断)
"""
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
# 添加邮件正文
msg.attach(MIMEText(body, 'html'))
# 添加附件
with open(attachment_path, 'rb') as file:
part = MIMEApplication(file.read(), Name=os.path.basename(attachment_path))
# 设置附件头信息
part['Content-Disposition'] = f'attachment; filename="{os.path.basename(attachment_path)}"'
msg.attach(part)
# 创建SMTP连接
if smtp_port == 465:
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
else:
server = smtplib.SMTP(smtp_server, smtp_port)
if use_tls:
server.starttls() # 启用TLS加密
# 登录邮箱服务器
server.login(sender_email, password)
# 发送邮件
server.sendmail(sender_email, receiver_email, msg.as_string())
# 关闭连接
server.quit()
print("邮件发送成功!")
# ======================== 使用示例 ========================
if __name__ == "__main__":
# 邮箱配置(请替换为实际信息)
SMTP_SERVER = "smtp.163.com" # 其他常见:QQ邮箱->smtp.qq.com, Gmail->smtp.gmail.com
SMTP_PORT = 465 # SSL加密端口(推荐): 163/QQ->465, Gmail->465; 非加密端口: 25(不推荐)
SENDER_EMAIL = "your_email@163.com" # 发件人邮箱
PASSWORD = "your_authorization_code" # 邮箱密码或授权码(注意:非登录密码,需在邮箱设置中获取)
RECEIVER_EMAIL = "receiver@example.com" # 收件人邮箱
# 邮件内容
SUBJECT = "测试带附件的邮件"
BODY = """
<h1>Python邮件测试</h1>
<p>这是一封来自Python程序的测试邮件,包含附件。</p>
<p style="color:blue;">邮件内容支持HTML格式!</p>
"""
# 附件路径(使用绝对路径确保文件可访问)
File_PATH = os.path.abspath("./test_file.txt") # 替换为实际文件路径
# 创建测试附件(如果不存在)
if not os.path.exists(File_PATH):
with open(File_PATH, 'w') as f:
f.write("这是一个测试附件内容\n创建时间:" + str(datetime.now()))
# 发送邮件
send_email_with_attachment(
smtp_server=SMTP_SERVER,
smtp_port=SMTP_PORT,
sender_email=SENDER_EMAIL,
password=PASSWORD,
receiver_email=RECEIVER_EMAIL,
subject=SUBJECT,
body=BODY,
attachment_path=File_PATH
)
运行 python send_email_1.py
使用说明:
-
邮箱配置:
- 需要开启邮箱的SMTP服务(登录邮箱设置中开启)
- 使用授权码而非登录密码(在邮箱安全设置中生成)
- 常用邮箱服务器设置:
- 163邮箱:
smtp.163.com, 端口465(SSL) - QQ邮箱:
smtp.qq.com, 端口465(SSL) - Gmail:
smtp.gmail.com, 端口465(SSL),需开启"低安全性应用访问"
- 163邮箱:
-
参数说明:
attachment_path:支持任何文件类型(txt、pdf、图片等)body:支持HTML格式(如需纯文本,将'html'改为'plain')
-
错误处理:
- 如果发送失败会抛出异常(如认证失败、网络问题等)
- 建议在调用时添加try-except块捕获
smtplib.SMTPException
常见问题解决:
-
认证失败:
- 确认使用授权码而非邮箱密码
- 检查是否开启SMTP服务
- Gmail需允许"不够安全的应用"
-
连接超时/被拒绝:
- 检查防火墙是否开放SMTP端口
- 尝试更换端口(465/587/25)
- 海外邮箱(如Gmail)可能需要科学上网
-
附件大小限制:
- 大多数邮箱限制附件不超过20MB
- 大文件建议使用云存储分享链接
扩展功能:
如需发送多个附件,可修改为:
def add_attachments(msg, file_paths):
for file_path in file_paths:
with open(file_path, 'rb') as file:
part = MIMEApplication(file.read(), Name=os.path.basename(file_path))
part['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"'
msg.attach(part)
将此程序保存为 send_email_1.py 文件,替换实际邮箱信息后即可运行。
804

被折叠的 条评论
为什么被折叠?



