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

使用MIMEMultipart()在Python中发送带有网页文件附件的邮件

发布时间:2023-12-25 18:34:52

以下是使用MIMEMultipart()在Python中发送带有网页文件附件的邮件的例子:

首先,我们需要导入所需的库:

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

接下来,我们需要设置发送邮件的相关参数:

# 邮件发送者和接收者
sender = "sender@example.com"
receiver = "receiver@example.com"

# 邮件主题和正文
subject = "带有网页文件附件的邮件"
body = "这是一封带有网页文件附件的测试邮件。"

# 邮件附件
attachment_path = "path/to/attachment.html"

然后,我们需要创建一个MIMEMultipart对象,将邮件正文和附件添加到其中:

# 创建一个MIMEMultipart对象
message = MIMEMultipart()

# 添加邮件正文
message.attach(MIMEText(body, "plain"))

# 读取附件文件并添加到邮件中
with open(attachment_path, "rb") as attachment_file:
    attachment = MIMEApplication(attachment_file.read(), _subtype="html")
    attachment.add_header("Content-Disposition", "attachment", filename="attachment.html")
    message.attach(attachment)

接下来,我们需要使用SMTP协议登录到邮件服务器,并发送邮件:

# 登录到邮件服务器
smtp_server = smtplib.SMTP("smtp.example.com", 587)
smtp_server.starttls()
smtp_server.login("username", "password")

# 发送邮件
smtp_server.sendmail(sender, receiver, message.as_string())
smtp_server.quit()

完整的代码如下:

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

# 邮件发送者和接收者
sender = "sender@example.com"
receiver = "receiver@example.com"

# 邮件主题和正文
subject = "带有网页文件附件的邮件"
body = "这是一封带有网页文件附件的测试邮件。"

# 邮件附件
attachment_path = "path/to/attachment.html"

# 创建一个MIMEMultipart对象
message = MIMEMultipart()

# 添加邮件正文
message.attach(MIMEText(body, "plain"))

# 读取附件文件并添加到邮件中
with open(attachment_path, "rb") as attachment_file:
    attachment = MIMEApplication(attachment_file.read(), _subtype="html")
    attachment.add_header("Content-Disposition", "attachment", filename="attachment.html")
    message.attach(attachment)

# 登录到邮件服务器
smtp_server = smtplib.SMTP("smtp.example.com", 587)
smtp_server.starttls()
smtp_server.login("username", "password")

# 发送邮件
smtp_server.sendmail(sender, receiver, message.as_string())
smtp_server.quit()

请注意,我们需要替换代码中的"sender@example.com"、"receiver@example.com"、"path/to/attachment.html"、"smtp.example.com"、"username"和"password"为实际的值。

这段代码创建了一个包含邮件正文和附件的MIMEMultipart对象,并使用SMTP协议登录到邮件服务器发送邮件。