Monday 19 January 2015

Python sending email using smtp


 #Sending email using python in a few simple steps. All you need a few libraries like smtplib, #email.mime.






import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

fromaddress = 'subhroneelganguly@gmail.com'  # example
toaddress = 'subhro1976@gmail.com' # example
text = 'This is my first email from python'  # Subject
username = 'subhroneelganguly'  # username
password ='password'                  # password
msg = MIMEMultipart()            # this is the message object
msg['From'] =fromaddress
msg['To'] = toaddress
msg['Subject'] = text            

msg.attach(MIMEText(text))   # Attaching subject tect to body, you can provide you own custom 
                                                  # body text.

server = smtplib.SMTP('smtp.googlemail.com')  # port is not mentioned in the argument, you can 

                                                                              #provide the port  after mail server address
                                                                             # i.e. smtp.googlemail.com,465
server.ehlo()            # say hello to server
server.starttls()        # telling server you want to tls encrypted connection.
server.ehlo()            # say hello to server once more
server.login(username,password)              # login to server server.sendmail(fromaddress,toaddress,msg.as_string())   # call sendmail function to send the mail. 

                                                                              # Convert the msg to string before sending.
server.quit()

No comments: