【发布时间】:2020-01-30 15:53:55
【问题描述】:
发送带有多个附件的邮件会删除附件文件名。附件名称更改为 ATT00001.xlsx。根据以下链接,在附件之前添加了“正文”部分,但没有运气。
https://exchange-server-guide.blogspot.com/2015/11/att00001.txt-file-fix-email-attachment-issue.html
供参考,分享如下代码sn-p。任何建议表示赞赏。
msg = MIMEMultipart()
ctype = content_type
maintype, subtype = ctype.split('/', 1)
msg['Subject'] = subject
msg['To'] = 'abc@sample.com'
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, 'abc@sample.com', msg.as_string())
smtp_client.quit()
【问题讨论】:
-
这里有很多缺失的
imports 和未声明的变量。 SMTP 发送部分并不是真正需要的(并且在适当的模块化代码中不应与消息组合代码纠缠在一起)。查看提供minimal reproducible example的指南
标签: python python-3.x email smtp smtplib