Share |

Saturday, July 09, 2016

How to send email in python using gmail, yahoo, hotmail?

In python, I have created a class by which we can send email through gmail, yahoo, hotmail or any other email service provider.


screen shot of python IDLE editor



Click here to view project online


Here is the complete code:


import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders

#-------------------------------Author-----------------------------------#
#                       chandan kumar ojha                               #
#                   Please don't change in code                          #
#                   It will reads to raise error                         #
#------------------------------------------------------------------------#

class Email(object):
    _message=None

    def __init__(self,to,eFrom,subject,body,Files=[]):
        msg = MIMEMultipart()
        msg['From'] = eFrom
        msg['To'] = to
        msg['Subject'] = subject
        msg.attach(MIMEText(body, 'plain'))

        for f in Files:
            #part = ('application',"octet-stream")
            #part.set_payload(open(f,"rb").read())
            part = MIMEApplication(open(f,'rb').read())
            #Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment', filename=str(os.path.basename(f)))
            msg.attach(part)
        self._message = msg

    def sendEmail(self,host,port,username,password):
        server = smtplib.SMTP(host, port)
        server.starttls()
        server.login(username,password)
        server.sendmail(self._message['From'],self._message['To'],self._message.as_string())
        server.quit()

# example To send email- Uncomment below line to send email
if __name__ == '__main__':
    Attachmets = ['c:\\Directory Name\\sub Directory\\File Name.Ext', 'c:\\Directory Name\\sub Directory\\File2 Name.Ext']
    mail = Email("ToEmailAddress@gmail.com","youemailAddress@gmail.com","test-SubjectLine","this is a body Text",Attachmets)
    mail.sendEmail('smtp.gmail.com',587,'youemailAddress@gmail.com','password')
© 2016 All Rights Reserved | DMCA.com Protection Status