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

Python中通过MIMEBase模块发送带有附件的电子邮件

发布时间:2023-12-14 03:33:10

使用Python发送带有附件的电子邮件可以通过MIMEBase模块来实现。MIME(Multipurpose Internet Mail Extensions)是一种在电子邮件中进行多媒体数据扩展的标准,MIMEBase模块提供了对MIME类型消息的基本处理功能。

下面是一个使用MIMEBase模块发送带有附件的电子邮件的例子:

import smtplib
import os.path
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(sender_email, receiver_email, subject, message, attachment_path):
    # 创建一个MIMEMultipart对象
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = receiver_email
    msg["Subject"] = subject

    # 添加正文
    msg.attach(MIMEText(message, "plain"))

    # 检查附件文件是否存在
    if os.path.exists(attachment_path):
        # 创建一个MIMEBase对象,并设置附件的类型和文件名
        with open(attachment_path, "rb") as attachment:
            part = MIMEBase("application", "octet-stream")
            part.set_payload(attachment.read())

        # 使用Base64编码转换附件内容
        encoders.encode_base64(part)

        # 添加附件头部信息
        part.add_header(
            "Content-Disposition",
            f"attachment; filename= {os.path.basename(attachment_path)}",
        )

        # 将附件添加到消息中
        msg.attach(part)

    # 发送邮件
    with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
        smtp.starttls()
        smtp.login(sender_email, "your_password")
        smtp.send_message(msg)

# 示例使用Gmail SMTP服务器发送电子邮件
sender_email = "sender@gmail.com"
receiver_email = "receiver@gmail.com"
subject = "Test Email with Attachment"
message = "This is a test email with attachment."
attachment_path = "path/to/attachment.txt"

send_email(sender_email, receiver_email, subject, message, attachment_path)

在上面的例子中,首先导入了需要的模块,包括smtplib用于发送邮件、os.path用于检查附件文件是否存在、MIMEText用于创建文本消息、MIMEMultipart用于创建带有附件的消息、MIMEBase用于创建附件、encoders用于编码附件内容。

然后定义了一个send_email函数,该函数接受发送者邮箱、接收者邮箱、邮件主题、邮件正文、附件路径作为参数。

在函数体内,首先创建一个MIMEMultipart对象,并设置发送者、接收者和邮件主题。

然后使用MIMEText将邮件正文添加到消息中。

接下来检查附件文件是否存在,如果存在,则使用MIMEBase创建一个application/octet-stream类型的附件对象,并设置附件内容为文件内容。

然后使用encoders对附件内容进行Base64编码,并添加附件的头部信息。

最后将附件添加到消息中。

send_email函数的最后,使用smptlib.SMTP连接到SMTP服务器,并使用smtp.login方法进行身份验证。

最后,使用smtp.send_message方法发送消息。

在示例中,使用了Gmail的SMTP服务器来发送电子邮件,如果你想使用其他邮箱的SMTP服务器,请相应更改SMTP服务器的主机和端口,并将sender_emailsmtp.login中的密码更改为正确的值。

另外,附件路径也需要根据实际情况进行修改。

总结:

以上便是一个使用MIMEBase模块发送带有附件的电子邮件的例子。通过MIMEBase模块,我们可以创建一个带有附件的MIME类型的消息,并通过SMTP服务器将这个消息发送给接收者邮箱。这个例子可以作为一个起点,你可以根据实际需求进行相应的修改和扩展。