Search code examples
pythoncsvemailemail-attachmentssmtplib

Sending email with multiple attachments in Python


I am trying to attach 2 files to an email and it fails with - raise TypeError("set_content not valid on multipart") TypeError: set_content not valid on multipart

code :

date_string = f'{datetime.now():%Y-%m-%dT%H_%M_%S%z}'

def send_mail_with_excel(recipient_email, subject, content, date_time):
    input_file = "C:\\scripts\\mail_send\\remediated_data_" + date_time + ".csv"
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = SENDER_EMAIL
    msg['To'] = recipient_email
    msg.set_content(content)

    with open(input_file, 'rb') as f:
        file_data = f.read()
    msg.add_attachment(file_data, maintype="application", subtype="csv", filename=input_file)

    multiAbort_file = "C:\\scripts\\mail_send\\multi_aborts_data_"+ date_time + ".csv"
    if os.path.isfile(multiAbort_file):
        with open(multiAbort_file, 'rb') as f:
            file_data = f.read()
        msg.add_attachment(file_data, maintype="application", subtype="csv", filename=multiAbort_file)
        msg.set_content(content+"\n Note : there is another list of items that are aborted multiple times in multi_aborts file, please restart these to continue")

    with smtplib.SMTP('smtp-mail.outlook.com', 587) as smtp:
        smtp.starttls()
        smtp.login(SENDER_EMAIL, APP_PASSWORD)
        smtp.send_message(msg)

send_mail_with_excel(["abc@xyz.com"], "Remediated List of items" + date_string,
                                 "Remediated List of items " + date_string, date_string)

Whats wrong in the formation?


Solution

  • You should evaluate content fully before calling set_content - don't call set_content twice and do not call it after adding attachments.

    So change part of your code to look like this:

    multiAbort_file = "C:\\scripts\\mail_send\\multi_aborts_data_"+ date_time + ".csv"
    has_abort = os.path.isfile(multiAbort_file)
    
    if has_abort:
        content = content + "\n Note : there is another list of items that are aborted multiple times in multi_aborts file, please restart these to continue"
    
    msg.set_content(content)
    
    with open(input_file, 'rb') as f:
        file_data = f.read()
    msg.add_attachment(file_data, maintype="application", subtype="csv", filename=input_file)
    
    if has_abort:
        with open(multiAbort_file, 'rb') as f:
            file_data = f.read()
        msg.add_attachment(file_data, maintype="application", subtype="csv", filename=multiAbort_file)