Home » 2017 » August » 22 » Send mail using python : smtplib

6:48 PM
Send mail using python : smtplib

Hereby we shall try to understand a very basic program to send mail using python library smtplib

The smtplib in python defines a client object that can be used to send mail to any internet machine a SMTP listener daemon.

 

1. Create an SMTP object.

import smtplib

smtpObj=smtplib.SMTP(host,portNo);

Note that host or port number are optional.

host: the server where SMTP is running. example: smtp.gmail.com

port number: the port number where SMTP server is listening.

 

If the SMTP server is running on your local machine, you can give localhost.


 

sendmail is a method of SMTP object that is typically used to send mail. It takes 3 parameters:

sender  -> the email id of sender, string

receiver --> the email Ids of recepients, list of string

messsage --> the message to send.

 

Login to the SMTP server using login method:

smtpObj.login("username", "pasword");

In most of the cases, we have to start TLS security, before we call the sendmail method.

smtpObj.starttls();

Then you can call sendmail method to send the message.

msg='hi'
smtpObj.sendmail('[email protected]','[email protected]',msg);

 

You can create a multiline message also using """ in python

msg=""" this is a multiline

message to send

in python, to receiver

"""

If you have a gmail account, you can use gmail as your SMTP server:

Gmail SMTP details

 


To handle any exception here, we can use SMTPException:

try:

         <send mail>

except smtplib.SMTPException:
        print "Error: unable to send mail";


I will be sharing a basic program also on the same:

#!/usr/bin/python

import smtplib

sender="[email protected]"
receiver="[email protected]"
message="""This is a message
    for you
    my sweetheart"""

smtpOBJ=smtplib.SMTP("smtp.gmail.com:587");
smtpOBJ.starttls();
smtpOBJ.login("[email protected]","mypassword")
try:
    smtpOBJ.sendmail(sender,receiver,message);
    print "Message sent successfully"
except:
    print "Error in sending mail"

 

Try this its quite simple.

 
 

Category: Programming Languages | Views: 1008 | Added by: shanky | Tags: python, smtp, sendmail, smtplib | Rating: 0.0/0

Related blogs


You may also like to see:



Total comments: 0
ComForm">
avatar