0
votes

I am trying to send an email with both text and attachment and running into below error?

Removing the following block am able to send email but can't send the attachment, can anyone provide guidance on how to fix it?

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

CODE:-

import os,smtplib import subprocess,pprint,shlex from subprocess import Popen, PIPE, call from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart

def sendEmail(type,data):
    global originalradar
    global gerriturl,email,username
    body = '''%s''' % (data)
    msg = MIMEMultipart(body)
    # sender = '[email protected]'
    sender = '[email protected]'
    receivers = ['[email protected]']
    #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)

Error:-

Cannot attach additional subparts to non-multipart/*
1

1 Answers

2
votes

Your msg object is of type MIMEText. You need a MIMEMultipart object in order to add attachments.

Add the message body as @stark suggests:

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

Check this great tutorial where it talks about sending a mail with attachment.