Skip to content

Instantly share code, notes, and snippets.

@kaniblu
Last active September 16, 2019 13:56
Show Gist options
  • Save kaniblu/2283d076b994ed48a5d82c67ad496082 to your computer and use it in GitHub Desktop.
Save kaniblu/2283d076b994ed48a5d82c67ad496082 to your computer and use it in GitHub Desktop.
Send gmails using command-line
#!/usr/bin/env python
import io
import sys
import yaml
import pathlib
import argparse
import smtplib
import getpass
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:
sys.stderr.write("failed to send mail\n")
sys.stderr.write(e + "\n")
def create_parser():
parser = argparse.ArgumentParser(
description="Send gmails using command lines. (Recommended) Set-up a "
"file at ~/.gmailrc that contains your gmail username and "
"password. Also, don't forget to set-up an 'Application-"
"specific password' to minimize security risk. Find more "
"information at https://support.google.com/mail/answer/185833?hl=en"
)
parser.add_argument("-t", "--to",
help="Recipient of the email. If not provided, the "
"mail will be sent to the username instead.")
parser.add_argument("-s", "--subject", default="",
help="Subject of the email.")
parser.add_argument("-b", "--body", default="",
help="Contents of the email.")
parser.add_argument("-u", "--username",
help="Gmail username. Specifying this option will "
"override the username read from ~/.gmailrc.")
parser.add_argument("-p", "--password", action="store_true",
help="Gmail password. Specifying this option will "
"override the password read from ~/.gmailrc.")
return parser
def main(args):
username, password = None, None
gmailrc_path = pathlib.Path("~/.gmailrc").expanduser().absolute()
if gmailrc_path.exists() and not gmailrc_path.is_dir():
with open(gmailrc_path, "r") as f:
gmailrc = yaml.safe_load(f)
username, password = gmailrc.get("username"), gmailrc.get("password")
if args.username is not None:
username = args.username
if username is None:
raise ValueError(f"must provide a username")
if args.password:
password = getpass.getpass(f"Password for {username}")
if password is None:
raise ValueError(f"must provide a password")
if args.to is None:
if "@" in username:
recipient = username
else:
recipient = f"{username}@gmail.com"
else:
recipient = args.to
send_email(username, password, recipient, args.subject, args.body)
if __name__ == "__main__":
main(create_parser().parse_args())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment