Hi. Have you ever thought of sending a mail to your friends without opening the gmail website in your browser?….It takes a bit time for everyone in opening browser, logging into your account and then composing your email.But python can make your work simpler and faster.
In this blog I will explain you about the process of sending an email using python script through terminal and about the problems that are encountered by me during this process .
Here is a simple python code for sending an email through a terminal
SMTP stands for Simple Mail Transfer Protocol ,it is a protocol used for sending an email. smtplib is a module which is already pre-installed in a python package.This module helps us in connecting to an SMTP server.
First mistake:Create a python file named email.py and copy the above code into it and try to run it in the terminal and see what happens.You will receive an error message,”module smptlib doesnot exit”. Try to install it using the command
pip3 install python3 and try to run it . Once again you will receive the similar message that smtplib does not exit . But in the above paragraph I already mentioned that smtplib is pre-installed . What may be the reason?…..You received an error message because email is one of modules of python package. So you cannot name your python file with a module name like email.py
The first step in this process is to import all the necessary modules.
getpass is a built-in module which takes input in the form of a password.These two lines of code will import the smtplib and getpass modules.
The next step is connecting to an SMTP Server.For connecting to an SMTP server you need to have an SMTP server domain name .The domain name for the SMTP server will usually be the name of your email provider’s domain name, with smtp. in front of it ,for example “smtp.gmail.com”. The following piece of code will help us in connecting to the SMTP server through the port 587 . Make it sure that you store it to a variable as the rest of processes like logging in ,etc must know the email provider’s domin name.
ehlo() we can establish a connection to the server.
starttls() puts your SMTP connection in TLS mode.
Now the next step is logging into the SMTP server and sending the mail .The following piece of code will help you in that process.
a.sendmail('Your email address','To address','message')
You can take inputs from the user to fill the necessary details like email address,to address,etc.The final step is to quit the SMTP server and you can do it by
NOTE: Before running your python code make sure that you turn on the access to third party applications which is present in Sign-in and Security settings in your email account.
In this way python can help you to send mails directly through terminal.