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

Python发送带附件的HTML电子邮件(使用email.mime.text)

发布时间:2023-12-23 09:55:23

发送带附件的HTML电子邮件是通过Python的email库中的mime.text模块完成的。下面是一个使用示例,演示了如何通过Python发送带附件的HTML电子邮件。

首先,需要导入所需的库:

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

接下来,创建一个函数来设置邮件内容和附件:

def send_email_with_attachment(sender, receiver, subject, message, file_path):
    # 创建一个混合MIME对象,用于包含HTML内容和附件
    msg = MIMEMultipart()
    msg["From"] = sender
    msg["To"] = receiver
    msg["Subject"] = subject

    # 添加HTML内容到邮件
    msg.attach(MIMEText(message, "html"))

    # 添加附件到邮件
    attachment = open(file_path, "rb")

    # 创建一个MIMEBase对象来处理附件文件
    mime_base = MIMEBase("application", "octet-stream")

    # 读取附件文件内容并将其赋值给MIMEBase对象
    mime_base.set_payload(attachment.read())

    # 使用base64编码附件文件
    encoders.encode_base64(mime_base)

    # 添加附件的标题
    mime_base.add_header("Content-Disposition", f"attachment; filename= {file_path}")

    # 将附件添加到邮件
    msg.attach(mime_base)

    # 关闭附件文件
    attachment.close()

    # 发送邮件
    smtp_obj = smtplib.SMTP("smtp.example.com", 587)
    smtp_obj.starttls()
    smtp_obj.login("your_email@example.com", "your_password")
    smtp_obj.sendmail(sender, receiver, msg.as_string())
    smtp_obj.quit()

在上面的代码中,send_email_with_attachment函数接收发件人、收件人、主题、消息和文件路径作为参数。它创建一个MIMEMultipart对象,用来容纳HTML内容和附件。

然后,使用MIMEText类将HTML消息添加到邮件中。接下来,通过打开文件和创建MIMEBase对象,将附件添加到邮件中。附件的文件名使用add_header方法添加到MIMEBase对象中。

最后,通过SMTP服务器发送邮件。在这个例子中,使用SMTP服务器的域名和端口,然后使用登录凭据登录。最后一行使用SMTP对象的sendmail方法发送邮件,并使用quit方法关闭SMTP连接。

使用这个函数发送带附件的HTML电子邮件的示例代码如下:

sender = "your_email@example.com"
receiver = "recipient_email@example.com"
subject = "HTML email with attachment"
message = "<h1>Hello!</h1><p>This is a sample HTML email with attachment.</p>"
file_path = "path_to_your_file"

send_email_with_attachment(sender, receiver, subject, message, file_path)

上面的代码将发送一个带有HTML内容和附件的电子邮件。发件人、收件人、主题和消息可以根据实际需求进行修改,file_path需要替换为实际附件的文件路径。

要注意的是,在使用这个示例代码之前,需要安装smtplib库,并使用正确的SMTP服务器域名、端口,以及正确的登录凭据。

希望这个示例代码可以帮助你了解如何使用Python发送带附件的HTML电子邮件。