Monday, 16 June 2014

How to send email with attachments in python

Send email functionality is very useful functionality. for this we have to configured server configuration as your web email configuration.

If you have gmail email SMTP configuration then you have to configured as below with Send email functionality.


                
                import smtplib, os
                from email.mime.text import MIMEText
                from email.mime.multipart import MIMEMultipart
                from email.mime.base import MIMEBase
                from email import Encoders
 
                gmail_user = "ashish@example.com"
                gmail_name = "Ashish "
                gmail_pwd = "example@123"
                name='Ashish'
                attach='E:/test/test.pdf'
                body ="Dear %s ,\n\nPlease find the attached files.\n\nThanks and Regards:\nAshish" % (name)
                msg = MIMEMultipart()
                msg['From'] = gmail_name
                msg['To'] = "ashish1@example.com"
                msg['Subject'] = "Send email with attachment"
                msg.attach(MIMEText(body))
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)
                mailServer = smtplib.SMTP("smtp.gmail.com", 25)
                mailServer.ehlo()
                mailServer.starttls()
                mailServer.ehlo()
                mailServer.login(gmail_user, gmail_pwd)
                mailServer.sendmail(gmail_name, "ashish1@example.com", msg.as_string())   # name + e-mail address in the From: field
                mailServer.close()

2 comments: