-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailtool
executable file
·81 lines (68 loc) · 2.65 KB
/
mailtool
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
# This should only be run from a system with postfix installed
import argparse
import os
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
SMTPSERVER = os.environ.get('SMTP_SERVER', 'localhost')
SMTPUSER = os.environ.get('SMTP_USER', '')
SMTPPASSWORD = os.environ.get('SMTP_PASSWORD')
# MAIL_FROM gets used later to set the msg "from" field
MAIL_FROM = 'noreply+'+SMTPUSER if SMTPUSER else 'noreply'
ERROR_MSG = """
ERROR!
The email for this job was supposed to be located in {} but that file
wasn't generated for some reason. This almost never happens, so
look for something farther up in the job related to this subject for
clues as to what might have happened
"""
def get_args():
parser = argparse.ArgumentParser(description='Simple Mail Tool')
parser.add_argument('--to', '-t', required=True, help='To recipient')
parser.add_argument('--subject', '-s', required=True, help='Subject')
parser.add_argument('--attach', '-a', required=False, action='append',
help='Attach a file')
parser.add_argument('messagefile',
help='File containing the message to send')
return parser.parse_args()
def main():
args = get_args()
# https://stackoverflow.com/q/41639660/1154487
msg = MIMEMultipart('mixed')
try:
with open(args.messagefile) as mailfile:
txt = mailfile.read()
txt = ('<html><body>'
'<font face="Courier New, Courier, monospace">'
'<pre>' + txt + '</pre>'
'</font></body></html>')
body = MIMEText(txt, 'html')
msg.attach(body)
except Exception:
# Even if something goes wrong, we should send a message
body = MIMEText(ERROR_MSG.format(args.messagefile))
if args.attach:
for attach_file in args.attach:
try:
with open(attach_file, 'rb') as attachment:
part = MIMEApplication(attachment.read())
part.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(attach_file))
msg.attach(part)
except Exception:
print('Error attaching {}'.format(attach_file))
msg['Subject'] = args.subject
msg['From'] = MAIL_FROM + '@canonical.com'
msg['To'] = args.to
s = smtplib.SMTP(SMTPSERVER)
if SMTPUSER:
# Only login if we have credentials in the env
s.ehlo()
s.starttls()
s.login(SMTPUSER, SMTPPASSWORD)
s.send_message(msg)
s.quit()
if __name__ == '__main__':
main()