Public
Snippet $1655283 authored by Jignesh Vasoya

python-gmail.py

Edited
import os
import json
import argparse

server = None
CONST_USER = "user"
CONST_PASS = "pass"
CONST_GMAIL_SERVER = "smtp.gmail.com:587"

def connect(server_address, user, password):
	global server
	server = smtplib.SMTP(server_address)
	server.ehlo()
	server.starttls()
	server.login(user, password)
	print "Connect to gmail server"

def send(from_addr, to_addr, sub, body):
	body_text = body
	if os.path.exists(body) and os.path.isfile(body):
		with open(body) as bfile:
			body_text = bfile.read()

	msg = "\r\n".join([
		"From: %s" % from_addr,
		"To: %s" % to_addr,
		"Subject: %s" % sub,
		"",
		body_text
		])
	server.sendmail(from_addr, to_addr, msg)
	print "email sent successfully"

def argument_parsing():
	parser = argparse.ArgumentParser(description='Send an email using gmail as SMTP server')
	parser.add_argument('-t', action="store", dest="to", default='')
	parser.add_argument('-f', action="store", dest="frm", default='jignesh.vasoya@gslab.com')
	parser.add_argument('-c', action="store", dest="cred_file", default='/home/jignesh/.secret/mail_auth.json')
	parser.add_argument('-s', action="store", dest="sub", default='No Subject')
	parser.add_argument('-m', action="store", dest="msg")

	args = parser.parse_args()
	return args


def main(argv):
	try:
		args = argument_parsing()
		user = '<your username for gmail'
		password = '<your password for gmail>'
		connect(CONST_GMAIL_SERVER, user, password)
		send(args.frm, args.to, args.sub, args.msg)
		sys.exit(0)
	except Exception as excp:
		raise
		sys.exit(1)

if __name__ == '__main__':
	main(sys.argv)