My l3g3nd

There is no spoon

Sending Authenticated and Encrypted Email With Python

| Comments

This script is very generic and can be used anywhere to send an authenticated email. The email is also secure because it creates a STARTTLS session making sure no one can snoop in (except NSA I guess). Also it has a logging capability which logs errors and exceptions in /var/log/syslog but then the script has to be executed with root privileges. Obviously this can be changed and logging can be enabled in any other file if running as a root in not an option. Script is pretty much self explanatory but feel free to ask if you have any questions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/python

import smtplib, logging, string

# This is for logging any exceptions and/or errors.
# It will be logged in /var/log/syslog with message similar to
# '2014-08-18 16:24:58,064 ERROR service_start global name 'sendeail' is not defined'
logging.basicConfig(filename='/var/log/syslog', format='%(asctime)s %(levelname)s %(funcName)s %(message)s', level=logging.ERROR)

# This function is used for sending authenticated email. 
def sendemail(status,To, From, Server, port, username, password, bodymessage):
  try:  
      SUBJECT = status
      TO = To
      FROM = From
      text = bodymessage
      BODY = string.join(( "From: %s" % FROM, "To: %s" % TO, "Subject: %s" % SUBJECT , "", text), "\r\n")
      server = smtplib.SMTP()
      server.connect(Server, port)
      server.starttls()
      server.login(username, password)        
      server.sendmail(FROM, [TO], BODY)
      server.quit()
  except Exception, e:
      logging.error(e)
def main():
  sendemail(status,To, From, Server, port, username, password, bodymessage)

if __name__ == '__main__':
  main()

Just to extrapolate, this script can be called from another script where there is a requirement to send an authenticated and encrypted email. This can be done by calling the sendemail function from the authmail script. I have successfully tested this script with Gmail.

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/python

import authmail

def blah():
  subject = "This is informational"    
  body = "Looks good."
  authmail.sendemail(subject, 'To-Email', 'From-Email', 'Server', 587, 'Username', 'Password', body)

if __name__ == '__main__':
  blah()

This and other scripts can be checked at my github page.

Comments