
By: prometheus
July 7, 2016
Custom Python Script: Sending an Email Through Terminal

By: prometheus
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 script
2. Define the custom module for the sending function "sendemail"def sendemail(from,pass,to,subject,body):
msg=MIMEText(body)
msg['From']=from
msg['To']=to
msg['Subject']=subject
try:
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
smtpserver.ehlo()
print "logging into the email server"
smtpserver.login(from,pass) #login to the smtp server
smtpserver.sendmail(from,to,msg.as_string())
smtpserver.close()#close the connection
print "message transfer successfull."
except:
print "failure sending the message!"#catch an exception
3. Define the main functiondef main():
from=raw_input("enter your email(gmail) ID/n")
pass=getpass.getpass()
to=raw_input("enter receiver email ID/n")
subject=raw_input("enter subject/n")
body=raw_input("enter body/n")
sendemail(from,pass,to,subject,body)
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!