Demo entry 5862478

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

   

Submitted by anonymous on Aug 06, 2016 at 07:01
Language: Python. Code size: 2.0 kB.

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')

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).