SMTP Authenticated email using Python script

email-from-python-script

System administrators generally use the sendmail or mail utility from mailx to send emails. Which automatically send the email from username@hostname. But there are times when you want to send email from external email server and it requires SMTP authentication. Python is a very powerful scripting language and we can use this below simple script send SMTP authenticated emails.

#!/usr/bin/python

import smtplib

email_to = 'emailto@gmail.com'
username = 'username@sender-domain.com'
password = 'password of username@sender-domain.com'

smtpserver = smtplib.SMTP("sender-domain.com",25)
smtpserver.ehlo()
smtpserver.login(username,password)
header = 'To:' + email_to + '\n' + 'From: ' + username + '\n' + 'Subject: Python SMTP Auth\n'
msg = header + '\n\n This is a test message generated from python script \n\n'
smtpserver.sendmail(username, email_to, msg)
smtpserver.close()
print 'Email sent successfully'

About 

Sreejit is the founder of Server Management Plus. His motto is "If there's an easier way, Why do it any other way" and following it, he has created a lots of automation scripts for the company using which we are able to resolve issue at an extremely fast rate and save lots of time. He has a very keen interest in new technologies and spend most of his free time online researching about it apart from listening music and watching movies.