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

Python中使用MIMEMultipart()发送带有CSV文件附件的邮件

发布时间:2023-12-25 18:32:46

在Python中,我们可以使用email模块中的MIMEMultipart来发送带有CSV文件附件的邮件。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_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path):
    # 创建一个MIMEMultipart对象
    msg = MIMEMultipart()

    # 设置邮件主题和发件人、收件人信息
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    # 添加文本内容
    msg.attach(MIMEText(body, 'plain'))

    # 添加附件
    attachment = open(attachment_path, 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_path)
    msg.attach(part)

    # 发送邮件
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)  # 根据邮件服务器进行设置
        server.starttls()
        server.login(sender_email, sender_password)
        text = msg.as_string()
        server.sendmail(sender_email, receiver_email, text)
        server.quit()
        print("邮件发送成功")
    except Exception as e:
        print("邮件发送失败:", e)

# 示例用法
sender_email = 'your_email@gmail.com'
sender_password = 'your_password'
receiver_email = 'receiver_email@gmail.com'
subject = 'Test Email with Attachment'
body = 'This is a test email with attachment.'
attachment_path = 'path_to_attachment.csv'

send_email_with_attachment(sender_email, sender_password, receiver_email, subject, body, attachment_path)

在上述示例中,我们首先创建了一个MIMEMultipart对象msg,用于存储邮件主体内容和附件。然后,我们设置了发件人、收件人和邮件主题等信息。接下来,我们将邮件的文本内容添加到msg中,使用MIMEText来设置邮件的文本格式为plain

然后,我们打开要添加为附件的CSV文件,将其读入并编码为MIMEBase对象的payload。接着,我们将MIMEBase对象添加到msg中,并设置附件的文件名。

最后,我们通过SMTP服务器发送邮件,使用starttls()方法启用TLS加密,并使用login()方法登录发件人邮箱。然后,我们将msg对象转换为字符串格式,并使用 server.sendmail()方法发送邮件。最后,我们关闭服务器连接。

这就是一个使用MIMEMultipart发送带有CSV文件附件的邮件的例子。你需要根据自己的需求修改发件人、收件人、附件路径以及SMTP服务器的相关信息。