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

Python中使用email.MIMEMultipartMIMEMultipart()创建多部分邮件

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

在Python中,可以使用email模块中的MIMEMultipart类来创建多部分邮件,这种邮件可以包含文本、HTML、附件等多种类型的内容。MIMEMultipart类可以创建一个multipart/mixed类型的邮件,它可以包含文本内容、HTML内容和附件。

下面是一个使用MIMEMultipart创建多部分邮件的例子:

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

def send_email(from_addr, to_addrs, subject, text_body, html_body, attachments=[]):
    # 创建MIMEMultipart对象
    msg = MIMEMultipart('mixed')
    
    # 设置邮件主题和发件人信息
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = ', '.join(to_addrs)
    
    # 添加文本内容
    text_part = MIMEText(text_body, 'plain')
    msg.attach(text_part)
    
    # 添加HTML内容
    html_part = MIMEText(html_body, 'html')
    msg.attach(html_part)
    
    # 添加附件
    for attachment in attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(attachment, "rb").read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=attachment.split('/')[-1])
        msg.attach(part)
    
    # 发送邮件
    smtp = smtplib.SMTP('smtp.example.com', 587)
    smtp.starttls()
    smtp.login('your_email@example.com', 'your_password')
    smtp.sendmail(from_addr, to_addrs, msg.as_string())
    smtp.quit()

# 使用示例
from_addr = 'your_email@example.com'
to_addrs = ['recipient1@example.com', 'recipient2@example.com']
subject = 'Python Email Example'
text_body = 'This is the plain text email body.'
html_body = '<h1>This is the HTML email body.</h1>'
attachments = ['/path/to/attachment1.pdf', '/path/to/attachment2.jpg']

send_email(from_addr, to_addrs, subject, text_body, html_body, attachments)

上面的代码中,首先创建一个MIMEMultipart('mixed')对象来表示邮件的类型是multipart/mixed,它可以包含文本内容、HTML内容和附件。

然后,设置邮件的主题和发件人信息,使用MIMEText类创建文本内容和HTML内容的MIMEText对象,并将它们附加到MIMEMultipart对象中。

接着,使用MIMEBase类创建附件的MIMEBase对象,读取附件的内容,对内容进行base64编码,设置附件的Content-Disposition头部信息,并将附件对象附加到MIMEMultipart对象中。

最后,使用smtplib模块连接到SMTP服务器,登录邮箱账号,调用sendmail()方法发送邮件,最后调用quit()方法关闭连接。