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

使用email.mime.text发送包含附件和HTML内容的中文邮件

发布时间:2024-01-11 10:36:45

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_with_attachment():

    # 设置收件人和发件人

    sender_email = "your_email@gmail.com"

    receiver_email = "receiver_email@gmail.com"

    # 创建包含附件的邮件

    message = MIMEMultipart()

    message["From"] = sender_email

    message["To"] = receiver_email

    message["Subject"] = "测试邮件"

    # 添加邮件正文内容

    message.attach(MIMEText("<h1>这是一封包含附件和HTML内容的测试邮件</h1>", "html"))

    # 添加附件

    filename = "attachment.pdf"

    attachment = open(filename, "rb")

    # 设置附件的MIME类型

    mime_type = "application/pdf"

    # 创建附件对象

    attachment_obj = MIMEBase("application", "octet-stream")

    # 读取附件内容并进行编码

    attachment_obj.set_payload(attachment.read())

    encoders.encode_base64(attachment_obj)

    # 设置附件的文件名

    attachment_obj.add_header("Content-Disposition", f"attachment; filename={filename}")

    # 将附件对象添加到邮件中

    message.attach(attachment_obj)

    # 关闭附件文件

    attachment.close()

    # 发送邮件

    with smtplib.SMTP(host="smtp.gmail.com", port=587) as server:

        server.starttls()

        server.login(sender_email, "your_password")

        server.sendmail(sender_email, receiver_email, message.as_string())

send_email_with_attachment()

以上是一个发送包含附件和HTML内容的邮件的示例代码,主要使用了email.mime.textemail.mime.multipart模块来实现。在代码中,首先设置了收件人和发件人的email地址。

然后,创建了一个MIMEMultipart对象来构建邮件的整体结构,并设置了发件人、收件人和主题。接下来,使用MIMEText添加了邮件的HTML内容。

然后,打开要添加为附件的文件,并读取其内容。设置附件的MIME类型,创建附件对象,并将附件内容进行编码。设置附件的文件名和内容类型,并将附件对象添加到邮件中。最后,发送邮件。

需要注意的是,示例代码中使用了Gmail的SMTP服务器来发送邮件,所以需要替换hostportsender_emailyour_password为您自己的信息。另外,您需要确保附件文件存在,并且设置正确的文件名和MIME类型。

这是一个使用email.mime.text发送包含附件和HTML内容的中文邮件的示例。您可以根据实际情况进行修改和扩展,以满足您的需求。