#!/usr/bin/env python

import io
import sys
import argparse
import smtplib


def send_email(user, pwd, recipient, subject, body):
    gmail_user = user
    gmail_pwd = pwd
    FROM = user
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print('successfully sent the mail')
    except Exception as e:
        print("failed to send mail")
        print(e)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("username", type=str)
    parser.add_argument("password", type=str)
    parser.add_argument("recipient", type=str)
    parser.add_argument("-s", "--subject", type=str, default=None)
    parser.add_argument("-b", "--body", type=str, default=None)

    args = parser.parse_args()

    if args.body is None:
        input_stream = sys.stdin
    else:
        input_stream = io.StringIO(args.body)

    body = input_stream.read()
    subject = args.subject if args.subject is not None else ""
    send_email(args.username, args.password, args.recipient, subject, body)
