746
|
1 #!/usr/bin/env python
|
|
2 # -*- coding: utf-8 -*-
|
|
3
|
|
4 """
|
|
5
|
|
6 See:
|
|
7 - http://pymotw.com/2/smtplib/
|
|
8 - http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/
|
|
9 - https://github.com/CognitiveNetworks/daily-reports/blob/master/send_added_tv_count.py
|
|
10 """
|
|
11
|
|
12 import argparse
|
|
13 import email.utils
|
|
14 import os
|
|
15 import smtplib
|
|
16 import sys
|
|
17 from email.mime.text import MIMEText
|
|
18
|
|
19 __all__ = ['main']
|
|
20
|
|
21 class MailSender(object):
|
|
22
|
|
23 def __init__(self, host, sender, password, port=587, type='plain'):
|
|
24 self.host = host
|
|
25 self.sender = sender
|
|
26 self.password = password
|
|
27 self.port = port
|
|
28 self.type = type
|
|
29
|
|
30 def __call__(self, message, *recipients, **headers):
|
|
31
|
|
32 assert recipients
|
|
33
|
|
34 # construct the message
|
|
35 msg = MIMEText(message, self.type)
|
|
36 headers.setdefault('From', self.sender)
|
|
37 headers.setdefault('To', ','.join(recipients))
|
|
38 for key, value in headers.items():
|
|
39 msg[key] = value
|
|
40
|
|
41 # connect to mail server
|
|
42 server = smtplib.SMTP(self.host, self.port)
|
|
43 try:
|
|
44 server.set_debuglevel(True)
|
|
45
|
|
46 # identify ourselves, prompting server for supported features
|
|
47 server.ehlo()
|
|
48
|
|
49 # If we can encrypt this session, do it
|
|
50 if server.has_extn('STARTTLS'):
|
|
51 server.starttls()
|
|
52 server.ehlo() # re-identify ourselves over TLS connection
|
|
53
|
|
54 # login
|
|
55 server.login(self.sender, self.password)
|
|
56
|
|
57 # send the email
|
|
58 server.sendmail(self.sender, recipients, msg.as_string())
|
|
59 finally:
|
|
60 server.quit()
|
|
61
|
|
62 def main(args=sys.argv[1:]):
|
|
63
|
|
64 # parse command line
|
|
65 parser = argparse.ArgumentParser(description=__doc__)
|
|
66 parser.add_argument('host')
|
|
67 parser.add_argument('sender')
|
|
68 parser.add_argument('password')
|
|
69 parser.add_argument('-r', '--recipients', dest='recipients',
|
|
70 nargs='+', required=True,
|
|
71 help="recipients")
|
|
72 parser.add_argument('-m', '--message', dest='message', required=True)
|
|
73 parser.add_argument('--port', dest='port', type=int, default=587,
|
|
74 help="port to connect to [DEFAULT: %(default)s]")
|
|
75 options = parser.parse_args(args)
|
|
76
|
|
77 message = options.message
|
|
78
|
|
79 # instantiate sender
|
|
80 sender = MailSender(options.host, options.sender, options.password, options.port)
|
|
81
|
|
82 # send email
|
|
83 sender(message, *options.recipients)
|
|
84
|
|
85
|
|
86 if __name__ == '__main__':
|
|
87 main()
|