Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import json
- import smtplib
- from email.mime.text import MIMEText
- def read_file(filename):
- """ Read contents of file. """
- f = open(filename)
- contents = f.read()
- f.close()
- return contents
- def parse_email(filename):
- """ --------------------
- String -> Dictionary
- --------------------
- Read given json file, and parse it.
- """
- return json.loads(read_file(filename))
- def send_email(msg_data):
- """ Given message data, send email. Expects the following:
- username, password, subject, message, sender, recipient
- """
- # Sender, recipient, and message content
- msg = MIMEText(msg_data['message'])
- msg['Subject'] = msg_data['subject']
- msg['From'] = msg_data['sender']
- msg['To'] = msg_data['recipient']
- # Login to account, and send email.
- username = msg_data['username']
- password = msg_data['password']
- server = smtplib.SMTP('smtp.gmail.com:587')
- server.starttls()
- server.login(username, password)
- server.sendmail(msg['From'], msg['To'], msg.as_string())
- server.quit()
- def process_email(filename):
- """ --------------------------------------------------------
- String -> SideEffect(Send email) | Print failure message
- --------------------------------------------------------
- Given json file containing email information, either send
- email, or print out an error message.
- """
- try:
- email_data = json.loads(read_file(filename))
- except:
- print "Couldn't parse: {}. Check that it has these fields: username, password, subject, message, sender, recipient".format(filename)
- return 1
- try:
- send_email(email_data)
- print "Sent email for {}".format(filename)
- except:
- print "Couldn't send email for {}. Is your password right?".format(filename)
- return 1
- return 0
- # Get email files
- email_files = filter(lambda f: f.endswith('.json'), os.listdir('.'))
- map(process_email, email_files)
- # { "username": "dela3499"
- # , "password": "bsvrvrzoelmfasj2" # app-specific password from Google
- # , "sender": "dela3499@gmail.com"
- # , "recipient": "dela3499+test@gmail.com"
- # , "subject": "Test 3"
- # , "message": "This is a test."
- # }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement