forked from Carcarcarson/sendmail-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsendmail.py
More file actions
73 lines (68 loc) · 2 KB
/
sendmail.py
File metadata and controls
73 lines (68 loc) · 2 KB
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
# coding: UTF-8
import smtplib
import os
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(mail_host, mail_port, mail_from, mail_to, msg, auth= None):
# connect smtp server, set debug to see reply information
smtp = smtplib.SMTP(mail_host, mail_port)
smtp.set_debuglevel(1)
# authentication
if auth :
smtp.starttls()
smtp.login(*auth)
# send mail
smtp.sendmail(mail_from, mail_to, msg.as_string())
# quit
smtp.quit()
def get_message(mail_from, mail_to, subject, body, files=[], infiles=[]):
msg = MIMEMultipart('alternative')
# from, to, subject
msg["From"] = mail_from
msg["To"] = ";".join(mail_to)
msg['Subject'] = subject
# body text html
html = '<div dir="auto" nkid="Body">'+body+'</div>' # nkid is used to differentiate from infiles
# infiles as base64 string
inb64s = []
for infile in infiles :
file_ = open(infile,'rb')
b64 = "<p>#File:"+os.path.split(infile)[-1]+"<br>"
b64 += base64.b64encode(file_.read()).decode()+"</p>"
file_.close()
inb64s.append(b64)
# body infiles html
if len(inb64s) :
html += '<div dir="auto" nkid="InFiles">'+''.join(inb64s)+'</div>'
content = MIMEText(html, 'html', 'UTF-8')
msg.attach(content)
# attach
for file_ in files :
attach = MIMEText(open(file_, "rb").read(), "base64", "UTF-8")
attach['Content-Type'] = 'application/octet-stream'
attach['Content-Disposition'] = 'attachment; filename=%s' % os.path.split(file_)[-1]
msg.attach(attach)
# end
return msg
if __name__ == "__main__":
# host:port
mail_host = "host"
mail_port = 587
# mail from and mail to
mail_from = "from_address"
mail_to = ["to_address"]
# authentication
auth = ("from_address","password") # None for anonymous
# subject
subject = "Subject"
# body
body = "Body"
# attachment
attachments = []
# inline attachment
inline_attachments = []
# massage
msg = get_message(mail_from, mail_to, subject, body, attachments, inline_attachments)
# send
send_mail(mail_host, mail_port, mail_from, mail_to, msg, auth)