-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendmail.py
57 lines (52 loc) · 1.86 KB
/
sendmail.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
# sendmail.py - A mail-sending abstraction library
# Author: Simon Volpert <[email protected]>
# This program is free software, released under the Apache License, Version 2.0. See the LICENSE file for more information
import subprocess
import sys
import smtplib
import threading
from email.mime.text import MIMEText
email_from = 'nobody <[email protected]>'
def send(config, to, subject, text_body, headers={}, callback=None):
use_smtp = True
success = True
# Select email backend
for setting in ['server', 'login', 'passwd']:
if setting not in config or config[setting] == '':
use_smtp = False
if 'email_from' not in config.keys() or config['email_from'] == '':
config['email_from'] = email_from
# Create email message
message = MIMEText(text_body)
message['From'] = config['email_from']
message['To'] = to
message['Subject'] = subject
message['Auto-Submitted'] = 'auto-generated'
for header in headers.keys():
message[header] = headers[header]
# Send the message
if use_smtp:
try:
server = smtplib.SMTP(config['server'])
server.login(config['login'], config['passwd'])
server.sendmail(message['From'], message['To'], message.as_string())
server.quit()
except KeyboardInterrupt:
sys.exit()
except:
print('SMTP failed: %s' % sys.exc_info()[1])
success = False
else:
try:
server = subprocess.Popen(['/usr/sbin/sendmail','-i', message['To']], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
server.communicate(bytes(message.as_string(), 'UTF-8'))
except:
print('Sendmail failed: %s' % sys.exc_info()[1])
success = False
if callback is not None:
callback(success)
return success
def background_send(config, to, subject, text_body, headers={}, callback=None):
subthread = threading.Thread(target=send, args=(config, to, subject, text_body, headers, callback), daemon=True)
subthread.start()