Zhiyi Zhang | 576aad1 | 2017-10-03 15:41:53 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | import sys |
| 3 | import smtplib |
| 4 | import argparse |
| 5 | import socket |
| 6 | from ConfigParser import SafeConfigParser |
| 7 | from email.mime.multipart import MIMEMultipart |
| 8 | from email.mime.text import MIMEText |
| 9 | |
| 10 | socket.setdefaulttimeout(10) |
| 11 | |
| 12 | # init arg parser and parse |
| 13 | parser = argparse.ArgumentParser(description='Email-challenge-sender for NDNCERT') |
| 14 | parser.add_argument("email", help="the receiver email address") |
| 15 | parser.add_argument("secret", help="the secret of the challenge") |
| 16 | parser.add_argument("caName", help="the CA name") |
| 17 | args = parser.parse_args() |
| 18 | |
| 19 | # open config |
| 20 | confParser = SafeConfigParser() |
| 21 | confParser.read('@SYSCONFDIR@/ndncert/ndncert-mail.conf') |
| 22 | |
| 23 | # read smtp settings |
| 24 | encrypt_mode = confParser.get('ndncert_smtp_settings', "ENCRYPT_MODE") |
| 25 | server = confParser.get('ndncert_smtp_settings', 'SMTP_SERVER') |
| 26 | port = confParser.get('ndncert_smtp_settings', 'SMTP_PORT') |
| 27 | username = confParser.get('ndncert_smtp_settings', 'SMTP_USER') |
| 28 | password = confParser.get('ndncert_smtp_settings', 'SMTP_PASSWORD') |
| 29 | |
| 30 | # read email settings |
| 31 | msg_from = confParser.get('ndncert_email_settings', 'MAIL_FROM') |
| 32 | subject = confParser.get('ndncert_email_settings', 'SUBJECT') |
| 33 | text = confParser.get('ndncert_email_settings', 'TEXT_TEMPLATE').format(args.secret, args.caName) |
| 34 | html = confParser.get('ndncert_email_settings', 'HTML_TEMPLATE').format(args.secret, args.caName) |
| 35 | |
| 36 | # form email message |
| 37 | msg = MIMEMultipart('alternative') |
| 38 | msg.attach(MIMEText(text, 'plain')) |
| 39 | msg.attach(MIMEText(html, 'html')) |
| 40 | msg['From'] = msg_from |
| 41 | msg['To'] = args.email |
| 42 | msg['Subject'] = subject |
| 43 | |
| 44 | # send email |
| 45 | if encrypt_mode == 'ssl': |
| 46 | smtp_server = smtplib.SMTP_SSL(server, port) |
| 47 | else: # none or tls |
| 48 | smtp_server = smtplib.SMTP(server, port) |
| 49 | |
| 50 | if encrypt_mode != 'none': |
| 51 | smtp_server.ehlo() |
| 52 | if encrypt_mode == 'tls': |
| 53 | smtp_server.starttls() |
| 54 | |
| 55 | if username != '' and password != '': |
| 56 | smtp_server.login(username, password) |
| 57 | |
| 58 | smtp_server.sendmail(msg_from, args.email, msg.as_string()) |
| 59 | smtp_server.close() |
| 60 | sys.exit() |