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' 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:
To handle any exception here, we can use SMTPException: try: <send mail> except smtplib.SMTPException:
Try this its quite simple. |
|
Related blogs
You may also like to see:
Total comments: 0 | |