python-2.7os.path

How to specify a new directory path to add attachment in mail using python


I am using below code to add attachment to the mail and sending it. In below code, files which are present in same directory as script gets attached.

My code is in 'testdir' folder and the files to attach are in 'testdir/testfiles' folder. How do I change the directory path below so that it attaches the files inside 'testdir/testfiles' folder.

Code :
import smtplib
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import Encoders
import os

def send_email(to, subject, text, filenames):
    try:
        gmail_user = 'xxxxx@gmail.com'
        gmail_pwd = 'xxxxx'
        msg = MIMEMultipart()
        msg['From'] = gmail_user
        msg['To'] = ", ".join(to)
        msg['Subject'] = subject
        msg.attach(MIMEText(text))
        for file in filenames:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(file, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file))
            msg.attach(part)

        mailServer = smtplib.SMTP("smtp.gmail.com:587")
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        mailServer.sendmail(gmail_user, to, msg.as_string())
        mailServer.close()
        print('successfully sent the mail')
    except smtplib.SMTPException,error:
        print str(error)

if __name__ == '__main__':
    attachment_file = ['t2.csv','t1.txt']
    to = "xxxxx@gmail.com"
    TEXT = "Hello everyone"
    SUBJECT = "Testing sending using gmail"
    send_email(to, SUBJECT, TEXT, attachment_file)

Solution

  • I created a new directory 'testfiles' and placed all files in it and list the files inside it using os.listdir. And iterate over all the files and attach it to mail.

    Updated code for attaching files to mail:

            dir_path = "/home/testdir/testfiles"
            files = os.listdir("testfiles")
            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)