Python how do i send multiple files in the email. I can send 1 file but how to send more than 1

29,111

Solution 1

If you want to attach files to the email you can use just iterate over files and attach them to the message. You also may want to add some text to the body. Here is the code:

import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def send_selenium_report():
    dir_path = "G:/test_runners/selenium_regression_test_5_1_1/TestReport"
    files = ["SeleniumTestReport_part1.html", "SeleniumTestReport_part2.html", "SeleniumTestReport_part3.html"]

    msg = MIMEMultipart()
    msg['To'] = "[email protected]"
    msg['From'] = "[email protected]"
    msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"

    body = MIMEText('Test results attached.', 'html', 'utf-8')  
    msg.attach(body)  # add message body (text or html)

    for f in files:  # add files to the message
        file_path = os.path.join(dir_path, f)
        attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
        attachment.add_header('Content-Disposition','attachment', filename=f)
        msg.attach(attachment)

    s = smtplib.SMTP()
    s.connect(host=SMTP_SERVER)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    print 'done!'
    s.close()

Solution 2

I have implemented this for sending mail from gmail.

import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders

def send_mail_gmail(username,password,toaddrs_list,msg_text,fromaddr=None,subject="Test mail",attachment_path_list=None):

    s = smtplib.SMTP('smtp.gmail.com:587')
    s.starttls()
    s.login(username, password)
    #s.set_debuglevel(1)
    msg = MIMEMultipart()
    sender = fromaddr
    recipients = toaddrs_list
    msg['Subject'] = subject
    if fromaddr is not None:
        msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    if attachment_path_list is not None:
        for each_file_path in attachment_path_list:
            try:
                file_name=each_file_path.split("/")[-1]
                part = MIMEBase('application', "octet-stream")
                part.set_payload(open(each_file_path, "rb").read())

                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment' ,filename=file_name)
                msg.attach(part)
            except:
                print "could not attache file"
    msg.attach(MIMEText(msg_text,'html'))
    s.sendmail(sender, recipients, msg.as_string())

You can pass multiple address as element of toaddrs_list to whom you want to send mail and multiple attachments files names with their path in attachment_path_list.

Share:
29,111
Riaz Ladhani
Author by

Riaz Ladhani

Updated on August 17, 2021

Comments

  • Riaz Ladhani
    Riaz Ladhani almost 3 years

    I have the following code to send a html file SeleniumTestReport_part1.html in an email in Python. I want to send more than 1 file in the email. How do can i do this?

    The files I want to send are: SeleniumTestReport_part1.html SeleniumTestReport_part2.html
    SeleniumTestReport_part3.html

    My code to send 1 file is:

    def send_selenium_report():
        fileToSend = r"G:\test_runners\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport_part1.html"
        with open(fileToSend, "rt") as f:
            text = f.read()
        msg = MIMEText(text, "html")
        msg['Subject'] = "Selenium ClearCore_Regression_Test_Report_Result"
        msg['to'] = "[email protected]"
        msg['From'] = "[email protected]"
    
        s = smtplib.SMTP()
        s.connect(host=SMTP_SERVER)
        s.sendmail(msg['From'], msg['To'], msg.as_string())
        s.close()
    

    Thanks, Riaz

  • Sid
    Sid about 6 years
    Thanks, I was having trouble with adding files. Just incase someone has a problem with the code: attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt") works to resolve encoding issue.