Ready to Start Your Career?

Custom Python Script: Sending an Email Through Terminal

prometheus 's profile image

By: prometheus

July 7, 2016

twirled-veneziana-cybraryEver wondered how you'd write up and send an email without launching the browser and the gateway portal of the serving entity? In this post, we describe how to send an email through a command line terminal. You'll be able to do so with little prior knowledge of Python or any other programming language. Lets get started...1. Import major modules required to carry out the operations

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 function

def 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!
Schedule Demo