Search code examples
pythongmailmimesmtplib

Send an attachment using Python script


I used following python script to send an attachment through gmail. But it can be used for send an attachment which is saved in the same folder python script is saved. I want to send an attachment which is saved in different folder. How can I do it by modifing this script? Thank you.

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
import datetime


smtpUser = ' '
smtpPass = ' '

toAdd = ' '
fromAdd = smtpUser

today = datetime.date.today()

subject  = 'Data File 01 %s' % today.strftime('%Y %b %d')
header = 'To :' + toAdd + '\n' + 'From : ' + fromAdd + '\n' + 'Subject : ' + subject + '\n'
body = 'This is a data file on %s' % today.strftime('%Y %b %d')

attach = 'Data on %s.csv' % today.strftime('%Y-%m-%d')

print header


def sendMail(to, subject, text, files=[]):
    assert type(to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = smtpUser
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file in files:
        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)

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo_or_helo_if_needed()
    server.starttls()
    server.ehlo_or_helo_if_needed()
    server.login(smtpUser,smtpPass)
    server.sendmail(smtpUser, to, msg.as_string())

    print 'Done'

    server.quit()


sendMail( [toAdd], subject, body, [attach] )

Solution

  • The fourth parameter of sendMail is a list of filenames, so you can do e.g.:

    sendMail(["[email protected]"], 
             "Subject", 
             "Dear sir..", 
             ["subdir/file1.zip", "subdirfile.zip"] )
    

    whereas subdir/file1.zip is relative to the path where you call the script. If you want to refer to a file somewhere completely else use /path/to/my/file1.zip, e.g. /home/user/file1.zip