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

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

发布时间:2023-12-25 18:33:35

在Python中,可以使用MIMEMultipart()模块来发送带有XML文件附件的邮件。下面是一个完整的使用例子:

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 = 'Email with XML file attachment'

# 创建一个MIMEMultipart对象作为邮件的根容器
msg = MIMEMultipart()

# 添加邮件正文
body = 'This is the body of the email.'
msg.attach(MIMEText(body, 'plain'))

# 添加XML文件附件
with open('path/to/xml/file.xml', 'rb') as file:
    attachment = MIMEApplication(file.read(), 'xml')
    attachment.add_header('Content-Disposition', 'attachment', filename='file.xml')
    msg.attach(attachment)

# 设置邮件的发件人、收件人和主题
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject

# 发送邮件
try:
    # 连接到SMTP服务器并登录
    smtp_obj = smtplib.SMTP('smtp.example.com', 587)  # 以smtp.example.com为例,具体根据实际情况填写
    smtp_obj.starttls()  # 启用TLS加密
    smtp_obj.login('smtp_username', 'smtp_password')  # 根据SMTP服务器要求填写登录用户名和密码

    # 发送邮件
    smtp_obj.sendmail(sender, receiver, msg.as_string())
    smtp_obj.quit()
    print('Email sent successfully!')
except Exception as e:
    print('An error occurred while sending the email:', str(e))

在上述代码中,我们首先导入了相关的模块,包括MIMEMultipart用于创建邮件的根容器、MIMEText用于添加邮件正文、MIMEApplication用于添加附件等。

然后,我们设置了发件人、收件人和邮件主题。接下来,创建了一个MIMEMultipart对象,作为邮件的根容器。

我们通过attach()方法将邮件正文添加到邮件容器中,并使用MIMEText指定正文的类型为纯文本。

然后,我们打开XML文件,将其读取的内容作为邮件附件添加到邮件容器中。通过add_header()方法设置附件的标题和文件名。

最后,我们设置邮件的发件人、收件人和主题,并使用sendmail()方法发送邮件。如果发送成功,则打印成功消息;如果发送失败,则打印错误信息。

需要注意的是,在实际使用中,要根据你所使用的SMTP服务器进行相应的配置,包括指定SMTP服务器的地址、端口以及登录用户名和密码。