在Python 3.6中重命名电子邮件附件

问题描述 投票:0回答:1

我有一个脚本可以在Python 2.7中重命名我的电子邮件附件,但是自从最近更新到Python 3.6以来,我在解决所有更改时遇到了问题。我放弃了旧脚本,因为它似乎不适用于更新版本的Python。

使用下面的脚本,如何更改电子邮件附件的名称?似乎可以很好地发送它们,但是我无法弄清楚如何正确地重命名附件。感谢您的协助。

# Importing Modules
import smtplib,imghdr
from email.message import EmailMessage

sender = "Me - Storm Alerts <[email protected]>"
recipient = "[email protected]"

msgTxt = "D:/testFolder/MSG.txt"
map2attach = "D:/testFolder/warningsMap.png"

# Create a text/plain message
with open(msgTxt) as fp:
    msg = EmailMessage()
    msg.set_content(fp.read())
    with open(map2attach, 'rb') as fp:
      img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',subtype=imghdr.what(None, img_data))
    msg.add_header('Content-Disposition',map2attach,filename='EmailTest.png')

msg['Subject'] = "NWS Alert"
msg['From'] = sender
msg['To'] = recipient

s = smtplib.SMTP('mail.myServer.com')
s.send_message(msg)
s.quit()
python-3.x email-attachments
1个回答
0
投票

[好吧,我想出了为将来需要帮助的任何人。

我必须替换以下两行:

msg.add_attachment(img_data, maintype='image',subtype=imghdr.what(None, img_data))
msg.add_header('Content-Disposition',map2attach,filename='EmailTest.png')

带有以下行:

msg.add_attachment(img_data, maintype='image',subtype=imghdr.what(None,img_data),filename="EmailTest.png")
© www.soinside.com 2019 - 2024. All rights reserved.