July 7, 2016
Custom Python Script: Sending an Email Through Terminal
July 7, 2016
import smtplib #this is required so that we can use email requisite modules
import getpass#to prevent shoulder surfing attacks thus hiding screen display while taken pass
from email.mime.text import MIMEText #to use MIMEText objects in our custom script2. Define the custom module for the sending function "sendemail"
smtpserver=smtplib.SMTP('smtp.gmail.com',587) #details of smtp server
print "trying to establish connection with mail server"
smtpserver.ehlo() #send an ehlo message to server
print "starting private session"
smtpserver.starttls()#establish encrypted session
print "logging into the email server"
smtpserver.login(from,pass) #login to the smtp server
smtpserver.close()#close the connection
print "message transfer successfull."
print "failure sending the message!"#catch an exception3. Define the main function
from=raw_input("enter your email(gmail) ID/n")
to=raw_input("enter receiver email ID/n")
if __name__=='__main__':main()4. Integrate all the pieces of code and save it into a single file with the extension .py.5. Run the script using "python file.py" on your terminal (or run it as bash script by first setting permissions using chmod and adding a line of code to starting of file with the location of python.)Note: We've described this process incorporating the sender email as Gmail. It can be changed to another program with appropriate port numbers and service locations of other providers.Note: This can be enhanced by using SMTP_SSL object to have a more secure SSL connection with a change in port number 465. If doing so, server_ssl_starttls() is not needed.
Thanks for reading this. Please comment below!