-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendemail.py
executable file
·57 lines (50 loc) · 1.78 KB
/
sendemail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
import os
import os.path as osp
import smtplib
from email.message import EmailMessage
SERVER = os.environ.get('EMAIL_SERVER', 'localhost')
PORT = os.environ.get('EMAIL_PORT', 25)
USERNAME = os.environ.get('EMAIL')
PASSWORD_FILE = os.environ.get('EMAIL_PASSWORD_FILE')
def send_email(to_addr, subject, content, from_addr=None, user=USERNAME,
password=None, password_file=PASSWORD_FILE, server=SERVER,
port=PORT, debug=False):
from_addr = from_addr or user
if not from_addr:
raise ValueError('either from_addr or user must be supplied')
if user and not password and password_file:
password = open(password_file).read().strip()
if isinstance(to_addr, (list, tuple)):
to_addr = ', '.join(to_addr)
if isinstance(content, EmailMessage):
msg = content
else:
msg = EmailMessage()
msg.set_content(content)
msg['To'] = to_addr
msg['From'] = from_addr
msg['Subject'] = subject
if debug:
print(f'Connecting to {server}:{port}')
with smtplib.SMTP(server, port) as s:
if user and password:
if debug:
print(f'Logging in as {user}')
s.starttls()
s.login(user, password)
s.send_message(msg)
if __name__ == '__main__':
import argparse
p = argparse.ArgumentParser()
p.add_argument('to_addr')
p.add_argument('subject')
p.add_argument('content')
p.add_argument('-f', '--from-addr')
p.add_argument('-u', '--user', default=USERNAME)
p.add_argument('-p', '--password')
p.add_argument('-s', '--server', default=SERVER)
p.add_argument('-P', '--port', default=PORT)
p.add_argument('-d', '--debug', action='store_true')
args = p.parse_args()
send_email(**vars(args))