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

使用email.mime.baseMIMEBase()在Python中构建MIME类型的电子邮件

发布时间:2024-01-04 05:33:24

在Python中,我们可以使用email.mime.base.MIMEBase()来构建MIME类型的电子邮件。

MIMEBaseemail.mime.base模块的一个类,它是MIME类型邮件的基类。它提供了一种方式来创建消息的主体部分,可以将其附加到MIMETextMIMEMultipart对象中。

以下是一个使用MIMEBase构建MIME类型电子邮件的例子:

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

# 构建邮件对象
msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = COMMASPACE.join(['recipient1@example.com', 'recipient2@example.com'])
msg['Subject'] = 'Example email with attachment'

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

# 添加邮件附件
attachment_path = '/path/to/attachment.pdf'
attachment_filename = 'attachment.pdf'

with open(attachment_path, 'rb') as file:
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(file.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', f'attachment; filename="{attachment_filename}"')
    msg.attach(part)

# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'sender@example.com'
password = 'password'

try:
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(username, password)
        server.send_message(msg)
    print('Email sent successfully')
except Exception as e:
    print(f'Failed to send email: {str(e)}')

在上面的例子中,我们首先导入了所需的模块和类。然后,我们创建了一个MIMEMultipart对象(代表邮件),并设置了发件人、收件人和主题。

接下来,我们添加了邮件正文,使用MIMEText类创建了一个文本对象,并将其附加到MIMEMultipart对象中。

然后,我们打开要附加的文件,并使用MIMEBase类创建了一个附件对象。我们读取文件的内容,并将其作为附件的有效负载。使用encoders模块对附件进行编码,并设置附件的Content-Disposition头部,指定附件的文件名。

最后,我们使用smtplib库设置SMTP服务器的信息,并使用SMTP服务器发送邮件。

以上是一个使用email.mime.base.MIMEBase()构建MIME类型电子邮件的例子。您可以根据自己的需要进行修改和扩展。