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

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

发布时间:2024-01-02 02:00:44

在Python中,可以使用email.mime.application模块来发送带有Word文档附件的邮件。以下是一个例子,演示如何使用该模块发送带有Word文档附件的邮件。

首先,需要导入相应的模块:

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

接下来,需要设置邮件的发送者、接收者、主题等等信息:

sender = "sender@example.com"
receiver = "receiver@example.com"
subject = "Sample Email with Attachment"

然后,创建一个带有附件的邮件对象:

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

接下来,需要读取Word文档的内容,并将其添加为附件:

with open("sample.docx", "rb") as f:
    attach = MIMEApplication(f.read(), _subtype="docx")
    attach.add_header("Content-Disposition", "attachment", filename="sample.docx")
    msg.attach(attach)

请注意,这里假设当前目录下存在一个名为"sample.docx"的Word文档。

最后,使用SMTP协议登录到邮件服务器,并发送邮件:

smtp_server = "smtp.example.com"
smtp_port = 587
username = "username"
password = "password"

try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(username, password)
    server.send_message(msg)
    server.quit()
    print("Email sent successfully!")
except smtplib.SMTPException as e:
    print("Error: unable to send email")
    print(e)

请根据实际情况修改上述代码中的邮件服务器、端口、用户名和密码。

这样,就可以使用email.mime.application模块发送带有Word文档附件的邮件了。注意,这个例子假定附件的文件名是"sample.docx",如果你想发送其他的Word文档附件,请修改代码中的文件名。