在 Python 中发送包含多个附件的电子邮件

Sending email with multiple attachments in Python

我正在尝试将 2 个文件附加到电子邮件中,但失败了 - 引发 TypeError("set_content 在 multipart 上无效") TypeError: set_content 对 multipart

无效

代码:

date_string = f'{datetime.now():%Y-%m-%dT%H_%M_%S%z}'

def send_mail_with_excel(recipient_email, subject, content, date_time):
    input_file = "C:\scripts\mail_send\remediated_data_" + date_time + ".csv"
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = SENDER_EMAIL
    msg['To'] = recipient_email
    msg.set_content(content)

    with open(input_file, 'rb') as f:
        file_data = f.read()
    msg.add_attachment(file_data, maintype="application", subtype="csv", filename=input_file)

    multiAbort_file = "C:\scripts\mail_send\multi_aborts_data_"+ date_time + ".csv"
    if os.path.isfile(multiAbort_file):
        with open(multiAbort_file, 'rb') as f:
            file_data = f.read()
        msg.add_attachment(file_data, maintype="application", subtype="csv", filename=multiAbort_file)
        msg.set_content(content+"\n Note : there is another list of items that are aborted multiple times in multi_aborts file, please restart these to continue")

    with smtplib.SMTP('smtp-mail.outlook.com', 587) as smtp:
        smtp.starttls()
        smtp.login(SENDER_EMAIL, APP_PASSWORD)
        smtp.send_message(msg)

send_mail_with_excel(["abc@xyz.com"], "Remediated List of items" + date_string,
                                 "Remediated List of items " + date_string, date_string)

队形有什么问题吗?

您应该在调用 set_content 之前全面评估 content - 不要调用 set_content 两次,也不要在 添加附件后调用它.

因此,将您的部分代码更改为如下所示:

multiAbort_file = "C:\scripts\mail_send\multi_aborts_data_"+ date_time + ".csv"
has_abort = os.path.isfile(multiAbort_file)

if has_abort:
    content = content + "\n Note : there is another list of items that are aborted multiple times in multi_aborts file, please restart these to continue"

msg.set_content(content)

with open(input_file, 'rb') as f:
    file_data = f.read()
msg.add_attachment(file_data, maintype="application", subtype="csv", filename=input_file)

if has_abort:
    with open(multiAbort_file, 'rb') as f:
        file_data = f.read()
    msg.add_attachment(file_data, maintype="application", subtype="csv", filename=multiAbort_file)