在 Python 中发送带有多个附件的电子邮件
Posted
技术标签:
【中文标题】在 Python 中发送带有多个附件的电子邮件【英文标题】:Sending email with multiple attachments in Python 【发布时间】:2021-12-30 10:36:14 【问题描述】:我正在尝试将 2 个文件附加到电子邮件中,但它失败了 - raise TypeError("set_content 在多部分上无效") TypeError: set_content 在多部分上无效
代码:
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)
队形出了什么问题?
【问题讨论】:
【参考方案1】:在调用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)
【讨论】:
非常感谢您帮助重新组织和清理。尝试过,它也适用于多个附件。以上是关于在 Python 中发送带有多个附件的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章
无法在python中使用MIME发送带有pdf附件的电子邮件