欢迎访问宙启技术站
智能推送

Python中利用MIMEApplication()发送带有TXT文件附件的邮件

发布时间:2023-12-24 23:45:18

在Python中,可以使用smtplib库进行电子邮件的发送,使用email库来构建邮件内容,包括邮件主题、发件人、收件人、正文等。下面是一个发送带有TXT文件附件的邮件的示例代码:

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

# 输入发件人、收件人、主题、正文内容
from_email = "<your_email@example.com>"
to_email = "<recipient@example.com>"
subject = "Email with TXT attachment"
body = "Please find the attached TXT file."

# 构建邮件对象
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject

# 添加正文
msg.attach(MIMEText(body, 'plain'))

# 添加附件
with open('path/to/attachment.txt', 'rb') as f:
    attachment = MIMEApplication(f.read(), _subtype="txt")
    attachment.add_header('Content-Disposition', 'attachment', filename='attachment.txt')
    msg.attach(attachment)

# 发送邮件
smtp_server = "<your_smtp_server>"
smtp_port = 587
smtp_username = "<your_username>"
smtp_password = "<your_password>"

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(smtp_username, smtp_password)
    server.send_message(msg)

print("Email sent successfully!")

在这个例子中,你需要将以下内容替换为你自己的信息:

1. <your_email@example.com>:发件人邮箱地址

2. <recipient@example.com>:收件人邮箱地址

3. <your_smtp_server>:SMTP服务器地址

4. <your_username>:发件人邮箱的用户名

5. <your_password>:发件人邮箱的密码

6. 'path/to/attachment.txt':附件的文件路径

首先,我们导入所需的模块。然后,我们设置发件人、收件人、主题和正文内容。接下来,我们创建一个MIMEMultipart对象,用于存储邮件内容和附件。我们将发件人、收件人和主题添加到头部信息中。然后,我们使用MIMEText对象添加正文内容。接着,我们使用MIMEApplication对象添加TXT文件附件,并设置其Content-Disposition头部信息。最后,我们使用smtplib库连接SMTP服务器,并通过starttls()方法设置TLS加密连接。然后,我们使用login()方法进行身份验证,并使用send_message()方法发送邮件。

以上就是通过Python发送带有TXT文件附件的电子邮件的示例代码。根据实际情况,你需要替换示例代码中的占位符信息,并确保本地文件路径正确。