📌  相关文章
📜  如何在 python 中将文件添加到电子邮件中(1)

📅  最后修改于: 2023-12-03 15:24:19.966000             🧑  作者: Mango

如何在 Python 中将文件添加到电子邮件中

发送电子邮件是 Python 中的一个常见任务,本文将介绍如何在 Python 中将文件添加到电子邮件中以便发送。

我们将使用 Python 的内置邮件库 smtplib 和 email 来实现邮件发送。首先我们需要导入这两个库:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

MIMEText 用于创建纯文本消息,MIMEMultipart 用于创建带附件的消息,MIMEApplication 则用于处理附件。

然后我们需要设置邮件服务器、发件人、收件人等邮件信息:

SMTP_SERVER = 'your_smtp_server_address'  # 设置 SMTP 服务器地址
SMTP_PORT = 'your_smtp_server_port'  # 设置 SMTP 服务器端口

sender = 'your_email_address'  # 发件人邮箱地址
password = 'your_email_password'  # 发件人邮箱密码

receiver = 'receiver_email_address'  # 收件人邮箱地址

subject = '邮件主题'  # 邮件主题
message = '邮件内容'  # 邮件内容

接下来创建邮件对象,并添加附件:

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject

# 添加附件
with open('file_path', 'rb') as f:
    attachment = MIMEApplication(f.read(), _subtype='pdf')
    attachment.add_header('content-disposition', 'attachment', filename='file_name.pdf')
    msg.attach(attachment)

其中 file_path 是要添加的附件文件路径,_subtype 表示附件类型(pdf、zip、txt 等),filename 表示附件名称。

最后将邮件发送出去:

server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()  # 开启 TLS 加密
server.login(sender, password)  # 登录发件人邮箱

message = MIMEText(message)
msg.attach(message)

server.send_message(msg)  # 发送邮件
server.quit()  # 关闭连接

发送邮件的过程中要注意开启 TLS 加密,并登录发送人邮箱。

到此,我们就成功地实现了在 Python 中将文件添加到电子邮件中的功能。