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

Python中使用email.MIMEMultipartMIMEMultipart()构建含有附件和文本内容的邮件

发布时间:2024-01-07 23:16:39

在Python中,可以使用email模块中的MIMEMultipart类来构建包含附件和文本内容的邮件。

首先,导入相关的模块:

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

接下来,设置发送方和接收方的邮件地址:

from_address = 'sender@example.com'
to_address = 'recipient@example.com'

然后,构建邮件的基本信息,包括主题、发件人和收件人:

subject = 'Sample Email with Attachment'

msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = Header(subject, 'utf-8')

接着,构建正文内容。可以使用MIMEText类来创建文本内容,并将其添加到邮件中:

text = """\
Hello,

This is a sample email with attachment. Please find the attached file.

Thanks,
Sender"""

body = MIMEText(text, 'plain', 'utf-8')
msg.attach(body)

然后,构建附件。可以使用MIMEApplication类来创建附件,并将其添加到邮件中。在创建附件时,需要指定文件路径和文件类型:

attachment_path = 'path/to/attachment.pdf'

with open(attachment_path, 'rb') as file:
    attachment = MIMEApplication(file.read())
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.pdf')
msg.attach(attachment)

最后,将邮件发送出去。首先,需要创建一个SMTP对象,并登录到SMTP服务器:

smtp_server = 'smtp.example.com'
username = 'username'
password = 'password'

server = smtplib.SMTP(smtp_server)
server.starttls()
server.login(username, password)

然后,使用send_message方法发送邮件:

server.send_message(msg)

最后,关闭SMTP连接:

server.quit()

完整的示例代码如下:

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


from_address = 'sender@example.com'
to_address = 'recipient@example.com'

subject = 'Sample Email with Attachment'

msg = MIMEMultipart()
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = Header(subject, 'utf-8')

text = """\
Hello,

This is a sample email with attachment. Please find the attached file.

Thanks,
Sender"""

body = MIMEText(text, 'plain', 'utf-8')
msg.attach(body)

attachment_path = 'path/to/attachment.pdf'

with open(attachment_path, 'rb') as file:
    attachment = MIMEApplication(file.read())
attachment.add_header('Content-Disposition', 'attachment', filename='attachment.pdf')
msg.attach(attachment)

smtp_server = 'smtp.example.com'
username = 'username'
password = 'password'

server = smtplib.SMTP(smtp_server)
server.starttls()
server.login(username, password)
server.send_message(msg)
server.quit()

以上代码是一个简单的示例,展示了如何在Python中使用email模块中的MIMEMultipart类构建带有附件和文本内容的邮件。实际使用中,可能还需要处理异常、验证收件人地址等其他任务。