尝试发送电子邮件附件时出错
Posted
技术标签:
【中文标题】尝试发送电子邮件附件时出错【英文标题】:Error while trying to send an email attachment 【发布时间】:2019-01-11 20:27:21 【问题描述】:我正在尝试发送包含文本和附件的电子邮件并遇到以下错误?
删除以下块可以发送电子邮件但无法发送附件,任何人都可以提供有关如何修复它的指导吗?
f = file(attachment_file_path )
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=attachment_file_path)
msg.attach(attachment)
代码:-
导入操作系统,smtplib 导入子流程,pprint,shlex 从子流程导入 Popen、PIPE、调用 从 email.mime.text 导入 MIMEText 从 email.MIMEMultipart 导入 MIMEMultipart
def sendEmail(type,data):
global originalradar
global gerriturl,email,username
body = '''%s''' % (data)
msg = MIMEMultipart(body)
# sender = 'wifici@company.com'
sender = 'username@company.com'
receivers = ['username@company.com']
#sendEmail(data)
attachment_file_path = './wifi_projects/wifi-ci/.git/rebase-apply/patch'
if type =='cherrypickfailure':
msg['Subject'] = 'CHERRYPICK FAILED '
msg['From'] = sender
msg['To'] = ', '.join(receivers)
try:
mail = smtplib.SMTP('relay.company.com', 25)
f = file(attachment_file_path )
attachment = MIMEMultipart(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename=attachment_file_path)
msg.attach(attachment)
msg.attach(MIMEText(body))
mail.sendmail(sender, receivers, msg.as_string())
print 'Email sent successfully'
except Exception as e:
print e
conflictedblocks = 'README': '<<<<<<< HEAD\nTRP\n=======\nTBD\n>>>>>>> <rdar://problem/42841519> Dummy radar\n'
conflictedblocks_string = ""
for key,value in conflictedblocks.items():
conflictedblocks_string += "<b><u>" +key + "</b></u>" +":" + "\n" + value + "\n"
sendEmail('cherrypickfailure',conflictedblocks_string)
错误:-
Cannot attach additional subparts to non-multipart/*
【问题讨论】:
【参考方案1】:您的msg
对象是MIMEText
类型。您需要一个 MIMEMultipart
对象才能添加附件。
按照@stark 的建议添加消息正文:
body = 'Your body content'
msg.attach(MIMEText(body))
检查this great tutorial,它谈到发送带有附件的邮件。
【讨论】:
我改成attachment = MIMEMultipart(f.read())
,也没用
我也改成了msg = MIMEMultipart(body)
,我得到了错误string payload expected: <type 'list'>
msg 应该是两个 MIMEText 的列表
@dashboard ,@stark :在您的建议没有帮助之后,我用我的最新代码更新了这个问题......您能否更具体地说明需要更改的内容?
我用msg.attach(MIMEText(body))
更新了我的代码并更新了问题,它没有帮助..我错过了什么?我应该删除任何东西吗?以上是关于尝试发送电子邮件附件时出错的主要内容,如果未能解决你的问题,请参考以下文章
在 gmail android 应用程序中发送带附件的电子邮件时出错
如何使用带有附件的 PEAR Mail 包使用 PHP 发送电子邮件
尝试通过电子邮件发送多个附件时出现 ActivityNotFoundException