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

Python邮件附件的处理(MIMEBase)

发布时间:2023-12-14 03:27:28

Python的smtplib库提供了用于发送电子邮件的功能,而email库则提供了处理邮件的功能,包括创建邮件、添加附件等。在email库中,MIMEBase类是一个基类,用于创建MIME邮件的基础部分,可以用来添加附件。

下面是一个使用MIMEBase类添加附件发送邮件的例子。

首先导入所需的库:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

然后创建MIMEMultipart对象,作为邮件的容器,可以包含文本、附件等多个部分:

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = 'Email with Attachment'

创建一个MIMEBase对象,并设置类型为'application', 'octet-stream'表示默认的二进制数据,将其作为附件添加到邮件中:

attachment = open('path/to/attachment.pdf', 'rb')

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='attachment.pdf')

msg.attach(part)

使用smtplib库发送邮件,需要提供SMTP服务器的地址和端口号,以及发件人的登录凭证:

server = smtplib.SMTP('smtp.example.com', 587)
server.login('sender@example.com', 'password')
server.sendmail('sender@example.com', 'receiver@example.com', msg.as_string())
server.quit()

完整的例子如下:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = 'Email with Attachment'

attachment = open('path/to/attachment.pdf', 'rb')

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename='attachment.pdf')

msg.attach(part)

server = smtplib.SMTP('smtp.example.com', 587)
server.login('sender@example.com', 'password')
server.sendmail('sender@example.com', 'receiver@example.com', msg.as_string())
server.quit()

在以上例子中,我们使用MIMEBase类创建了一个附件,并将其添加到了邮件中。在使用MIMEBase类时,需要注意设置附件的类型、文件名等相关信息。

使用MIMEBase类添加附件后,发送和接收邮件的步骤与普通邮件发送相同。