Advertisement
Guest User

Untitled

a guest
May 19th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. import os
  2. import json
  3. import smtplib
  4. from email.mime.text import MIMEText
  5.  
  6. def read_file(filename):
  7. """ Read contents of file. """
  8. f = open(filename)
  9. contents = f.read()
  10. f.close()
  11. return contents
  12.  
  13. def parse_email(filename):
  14. """ --------------------
  15. String -> Dictionary
  16. --------------------
  17. Read given json file, and parse it.
  18. """
  19. return json.loads(read_file(filename))
  20.  
  21. def send_email(msg_data):
  22. """ Given message data, send email. Expects the following:
  23. username, password, subject, message, sender, recipient
  24. """
  25. # Sender, recipient, and message content
  26. msg = MIMEText(msg_data['message'])
  27. msg['Subject'] = msg_data['subject']
  28. msg['From'] = msg_data['sender']
  29. msg['To'] = msg_data['recipient']
  30.  
  31. # Login to account, and send email.
  32. username = msg_data['username']
  33. password = msg_data['password']
  34.  
  35. server = smtplib.SMTP('smtp.gmail.com:587')
  36. server.starttls()
  37. server.login(username, password)
  38. server.sendmail(msg['From'], msg['To'], msg.as_string())
  39. server.quit()
  40.  
  41. def process_email(filename):
  42. """ --------------------------------------------------------
  43. String -> SideEffect(Send email) | Print failure message
  44. --------------------------------------------------------
  45. Given json file containing email information, either send
  46. email, or print out an error message.
  47. """
  48. try:
  49. email_data = json.loads(read_file(filename))
  50. except:
  51. print "Couldn't parse: {}. Check that it has these fields: username, password, subject, message, sender, recipient".format(filename)
  52. return 1
  53. try:
  54. send_email(email_data)
  55. print "Sent email for {}".format(filename)
  56. except:
  57. print "Couldn't send email for {}. Is your password right?".format(filename)
  58. return 1
  59. return 0
  60.  
  61. # Get email files
  62. email_files = filter(lambda f: f.endswith('.json'), os.listdir('.'))
  63.  
  64. map(process_email, email_files)
  65.  
  66. # { "username": "dela3499"
  67. # , "password": "bsvrvrzoelmfasj2" # app-specific password from Google
  68. # , "sender": "dela3499@gmail.com"
  69. # , "recipient": "dela3499+test@gmail.com"
  70. # , "subject": "Test 3"
  71. # , "message": "This is a test."
  72. # }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement