Skip to content

Instantly share code, notes, and snippets.

@gsquire
Last active August 29, 2015 14:26
Show Gist options
  • Save gsquire/55de46727eb8358c3ede to your computer and use it in GitHub Desktop.
Save gsquire/55de46727eb8358c3ede to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#
# author: Garrett Squire, gsquire
#
# 08/05/2015
#
import argparse
import os
import sys
from email.parser import Parser
import sendgrid
def sendmail_file(rfc_file):
with open(rfc_file, 'r') as mail:
headers = Parser().parse(mail)
# After parsing the email, setup the parameters for the SendGrid
# API usage.
sg_client = sendgrid.SendGridClient(os.environ['SENDGRID_API_KEY'])
mail = sendgrid.Mail()
mail.add_to(headers['to'])
mail.set_from(headers['from'])
mail.set_from_name(headers['sender'])
mail.set_subject(headers['subject'])
mail.set_date(headers['date'])
# This payload method returns a list of message objects. Text first, then
# html and we want return them as a string for the API.
mail.set_text(headers.get_payload()[0].as_string())
# We strip the first 4 lines out of the HTML because they are specifiying
# that it is an HTML document, thus unnecessary.
stripped_html = headers.get_payload()[1].as_string().split('\n')[4:]
mail.set_html('\n'.join(stripped_html))
status, msg = sg_client.send(mail)
if status == 200:
print 'Sent the email.'
else:
print 'Something went wrong: ' + msg
def sendmail_input(to, subject, from_email, text="", cc=[], bcc=[]):
"""
Form an email through the API with positional command line arguments.
"""
sg_client = sendgrid.SendGridClient(os.environ['SENDGRID_API_KEY'])
mail = sendgrid.Mail()
mail.add_to(to)
mail.set_subject(subject)
mail.set_from(from_email)
mail.set_text(text.read())
mail.add_cc(cc)
mail.add_bcc(bcc)
# Close the text file as it was opened during argument parsing.
text.close()
status, msg = sg_client.send(mail)
if status == 200:
print 'Sent the email.'
else:
print 'Something went wrong: ' + msg
def main():
# This is a when an email is read from an RFC 822 compliant file.
if len(sys.argv) == 2:
sendmail_file(sys.argv[1])
sys.exit(0)
args = argparse.ArgumentParser()
args.add_argument('--to', nargs='*', required=True)
args.add_argument('--subject', required=True)
args.add_argument('--from', required=True)
args.add_argument('--text', type=file, required=True)
args.add_argument('--cc', nargs='*')
args.add_argument('-bcc', nargs='*')
# This makes an accessible dictionary for the arguments.
cl_values = vars(args.parse_args())
sendmail_input(cl_values['to'], cl_values['subject'], cl_values['from'],
cl_values['text'], cl_values['cc'], cl_values['bcc'])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment