forked from ohidurbappy/random-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
python-send-email.py
85 lines (67 loc) · 2.39 KB
/
python-send-email.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
73
74
75
76
77
78
79
80
81
82
83
84
85
import os
import smtplib
from email import encoders as Encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(to,sender, subject, text,username=None,password=None,hostname="smtp.gmail.com",port=465, cc=None, bcc=None, reply_to=None, attach=None,
html=None, pre=False, custom_headers=None):
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = to
msg['Subject'] = subject
to = [to]
username=username if username else sender
if cc:
# cc gets added to the text header as well as list of recipients
if type(cc) in [str]:
msg.add_header('Cc', cc)
cc = [cc]
else:
cc = ', '.join(cc)
msg.add_header('Cc', cc)
to += cc
if bcc:
# bcc does not get added to the headers, but is a recipient
if type(bcc) in [str]:
bcc = [bcc]
to += bcc
if reply_to:
msg.add_header('Reply-To', reply_to)
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to
# display.
if pre:
html = "<pre>%s</pre>" % text
if html:
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgText = MIMEText(text)
msgAlternative.attach(msgText)
# We reference the image in the IMG SRC attribute by the ID we give it
# below
msgText = MIMEText(html, 'html')
msgAlternative.attach(msgText)
else:
msg.attach(MIMEText(text))
if attach:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
if custom_headers:
for k, v in custom_headers.iteritems():
msg.add_header(k, v)
if port in (465,):
mailServer = smtplib.SMTP_SSL(hostname, port)
else:
mailServer = smtplib.SMTP(hostname, port)
mailServer.ehlo()
if port in (587,):
mailServer.starttls()
if username and password:
mailServer.login(username, password)
mailServer.sendmail(username, to, msg.as_string())
mailServer.close()