-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsendmail.py
72 lines (59 loc) · 2.38 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import ConfigParser
def send_mail(send_from, send_to, subject, text, files=None,
data_attachments=None, server="smtp.office365.com", port=587,
tls=True, html=False, images=None,
username=None, password=None,
config_file=None, config=None):
if files is None:
files = []
if images is None:
images = []
if data_attachments is None:
data_attachments = []
if config_file is not None:
config = ConfigParser.ConfigParser()
config.read(config_file)
if config is not None:
server = config.get('smtp', 'server')
port = config.get('smtp', 'port')
tls = config.get('smtp', 'tls').lower() in ('true', 'yes', 'y')
username = config.get('smtp', 'username')
password = config.get('smtp', 'password')
msg = MIMEMultipart('related')
msg['From'] = send_from
msg['To'] = send_to if isinstance(send_to, basestring) else COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text, 'html' if html else 'plain') )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
for f in data_attachments:
part = MIMEBase('application', "octet-stream")
part.set_payload( f['data'] )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % f['filename'])
msg.attach(part)
for (n, i) in enumerate(images):
fp = open(i, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image{0}>'.format(str(n+1)))
msg.attach(msgImage)
smtp = smtplib.SMTP(server, int(port))
if tls:
smtp.starttls()
if username is not None:
smtp.login(username, password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()