使用AT00001删除电子邮件附件文件名

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

发送具有多个附件的邮件将删除附件文件名。附件名称更改为ATT00001.xlsx。按照以下链接,“ body”部分在附件之前添加,但没有运气。

https://exchange-server-guide.blogspot.com/2015/11/att00001.txt-file-fix-email-attachment-issue.html

供参考,共享以下代码段。任何建议表示赞赏。

msg = MIMEMultipart()
        ctype = content_type
        maintype, subtype = ctype.split('/', 1)
        msg['Subject'] = subject
        msg['To'] = '[email protected]'
        msg['From'] = sender
        smtp_client = smtplib.SMTP(smtp_host + ':' + smtp_port)
        smtp_client.starttls()
        smtp_client.login(sender, smtp_login_password)
        body_part = MIMEText(body, 'plain')
        msg.attach(body_part)
        for file_path in file_paths :
            temp_arr = file_path.split('/')
            file_name = temp_arr[len(temp_arr) - 1]
            msg.add_header('Content-Disposition', 'attachment', filename=file_name)
            fp = open(file_path, 'rb')
            attachment = MIMEBase(maintype, subtype)
            attachment.set_payload(fp.read())
            fp.close()
            encode_base64(attachment)
            msg.attach(attachment)
        smtp_client.sendmail(sender, '[email protected]', msg.as_string())
        smtp_client.quit() 
python-3.x email smtp smtpclient smtplib
1个回答
0
投票

您正在将Content-Disposition:添加到多部分容器中。您应该将其添加到每个身体部位。

更改此:

        msg.add_header('Content-Disposition', 'attachment', filename=file_name)
        fp = open(file_path, 'rb')
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
        fp.close()
        encode_base64(attachment)
        msg.attach(attachment)

类似

        attachment = MIMEBase(maintype, subtype)
        with open(file_path, 'rb') as fp:
            attachment.set_payload(fp.read())
        attachment.add_header('Content-Disposition', 'attachment', filename=file_name)
        encode_base64(attachment)
        msg.attach(attachment)

[我也自由地切换到使用上下文管理器(with语句)。

© www.soinside.com 2019 - 2024. All rights reserved.