尝试发送电子邮件附件时出错

时间:2018-08-03 23:31:04

标签: python

我正在尝试发送包含文本和附件的电子邮件,并遇到以下错误?

删除以下代码块可以发送电子邮件,但无法发送附件,任何人都可以提供有关修复方法的指导吗?

   f = file(attachment_file_path )
    attachment = MIMEText(f.read())
    attachment.add_header('Content-Disposition', 'attachment', filename=attachment_file_path)           
    msg.attach(attachment)

代码:-

导入os,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 个答案:

答案 0 :(得分:2)

您的msg对象的类型为MIMEText。您需要一个MIMEMultipart对象才能添加附件。

按照@stark的建议添加消息正文:

body = 'Your body content'
msg.attach(MIMEText(body))

检查this great tutorial中有关发送带有附件的邮件的信息。