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

Python中使用email.mime.application模块发送带有文档模板附件的邮件

发布时间:2024-01-02 02:06:03

在Python中,您可以使用email.mime.application模块来发送带有文档模板附件的邮件。下面是一个示例,说明如何使用该模块发送包含.docx文件附件的邮件。

首先,我们需要导入所需的模块和类。

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

接下来,我们需要设置邮件内容和附件。

# 发件人信息
sender = "your_email_address"
sender_password = "your_email_password"

# 收件人信息
receiver = "receiver_email_address"

# 邮件主题
subject = "Document Template"

# 邮件正文
body = "Please find attached the document template."

# 邮件附件
attachment_path = "path_to_document_template.docx"

然后,我们需要创建MIMEMultipart对象,并设置发件人、收件人、主题和正文。

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

msg.attach(MIMEText(body, "plain"))

接下来,我们需要打开并读取附件文件。

with open(attachment_path, "rb") as f:
    attachment = MIMEApplication(f.read(), _subtype="docx")
    attachment.add_header("Content-Disposition", "attachment", filename=attachment_path.split("/")[-1])
    msg.attach(attachment)

最后,我们可以使用SMTP协议发送邮件。

with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender, sender_password)
    server.send_message(msg)

完整的代码如下所示:

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

# 发件人信息
sender = "your_email_address"
sender_password = "your_email_password"

# 收件人信息
receiver = "receiver_email_address"

# 邮件主题
subject = "Document Template"

# 邮件正文
body = "Please find attached the document template."

# 邮件附件
attachment_path = "path_to_document_template.docx"

# 创建邮件对象
msg = MIMEMultipart()
msg["From"] = sender
msg["To"] = receiver
msg["Subject"] = subject

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

# 添加附件
with open(attachment_path, "rb") as f:
    attachment = MIMEApplication(f.read(), _subtype="docx")
    attachment.add_header("Content-Disposition", "attachment", filename=attachment_path.split("/")[-1])
    msg.attach(attachment)

# 发送邮件
with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender, sender_password)
    server.send_message(msg)

请确保替换示例代码中的发件人、收件人、密码和附件路径等信息。此外,还需要在发送邮件之前配置您的邮箱以允许通过SMTP协议发送邮件。

这是使用email.mime.application模块发送带有文档模板附件的邮件的一个例子。您可以根据自己的需求进行修改和调整。