Created
March 11, 2016 10:12
-
-
Save izinin/6e901527c262494fad2d to your computer and use it in GitHub Desktop.
sending email with python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import smtplib | |
import sys, getopt | |
import pdb | |
def main(argv): | |
helpMsg = """sendmail.py -c <smtp_srv> -o <smtp_port> -u <smtp_user> -p <smtp_passwd> | |
-s <mail_sender> -r <mail_recepients> -m <mail_msg> | |
""" | |
smtp_srv = '' | |
smtp_port = 0 | |
smtp_user = '' | |
smtp_passwd = '' | |
mail_sender = smtp_user | |
mail_recepients = [] | |
mail_msg = '' | |
try: | |
opts, args = getopt.getopt(argv,"hc:o:u:p:s:r:m:",["prefix="]) | |
except getopt.GetoptError: | |
print helpMsg | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-h': | |
print "test" #helpMsg | |
sys.exit() | |
elif opt in ("-c", "--srv"): | |
smtp_srv = arg | |
elif opt in ("-o", "--port"): | |
smtp_port = arg | |
elif opt in ("-u", "--user"): | |
smtp_user = arg | |
elif opt in ("-p", "--passwd"): | |
smtp_passwd = arg | |
elif opt in ("-s", "--sender"): | |
mail_sender = arg | |
elif opt in ("-r", "--recepients"): | |
mail_recepients = arg | |
elif opt in ("-m", "--msg"): | |
mail_msg = arg | |
if smtp_srv == '' or smtp_port == '' or smtp_user == '' or \ | |
smtp_passwd == '' or mail_recepients == '' or mail_msg == '': | |
print helpMsg | |
sys.exit() | |
if mail_sender == '': | |
mail_sender = smtp_user | |
if mail_recepients[0] == '[' and mail_recepients[-1] == ']': | |
mail_recepients = map(lambda x: x.strip(), mail_recepients[1:-1].split(',')) | |
try: | |
session = smtplib.SMTP(smtp_srv, smtp_port) | |
session.ehlo() | |
session.starttls() | |
session.ehlo | |
session.login(smtp_user, smtp_passwd) | |
session.sendmail(mail_sender, mail_recepients, mail_msg) | |
print "Successfully sent email" | |
except smtplib.SMTPException: | |
#pdb.set_trace() | |
print "Error: unable to send email" | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment