-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailmanager.py
124 lines (114 loc) · 4.22 KB
/
mailmanager.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# Barn Automation Email Manager
# Import Required Libraries
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
# Define Server Parameters
smtp_server = 'smtp.gmail.com'
smtp_port = 587
# Define Credentials - YES, I Know this is not best practice, but for now, it's a must.
address = "[email protected]"
passset = "St@nl3ys0lut!0n$t3ch"
# Define Email Sender Function
def send_email(recipient_list, content, files=None):
# Interpret Subject/Body from Content
subject = content['subject']
body = content['body']
html = content['html']
# Set Up MIME with Header Fields
if html != '':
message = MIMEMultipart("alternative", None,
[MIMEText(body), MIMEText(html,'html')])
elif files != None:
message = MIMEMultipart("alternative", None,
[MIMEText(body), MIMEText(body,'html')])
else:
message = MIMEText(body)
message['From'] = address
# Clean Up Recipient List and Prepare for Email Sender
recipient_list = [i for i in recipient_list if i]
recipients = COMMASPACE.join( recipient_list )
message['To'] = recipients
message['Date'] = formatdate(localtime=True)
message['Subject'] = subject
# Condition File Input
if files != None and isinstance(files, str):
files = [files] # Wrap as a List
# Attach Any Available Files
for f_nm in files or []:
with open(f_nm, "rb") as f_obj:
part = MIMEApplication( f_obj.read(), Name=basename(f_nm) )
# After File is Closed
part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(f_nm))
message.attach(part)
# Open SMTP Session and Send Mail
session = smtplib.SMTP(smtp_server, smtp_port)
session.starttls() # Enable Security
session.login(address, passset) # Log In to Server
# Load Content and Send
session.sendmail(address, recipient_list, message.as_string())
session.quit()
# Define Email Template Reader Function
def emailtemplate(path,subjectcontext=None,bodycontext=None,htmlcontext=None):
"""
Description of Template File Structure:
'''
*subject-line*
*body-content*
;; *return-character*
*more body-content*
*cont'd*
{{replacement}}
*more body*
<html>
*html-body-content*
'''
Use of the {{context}} formatting option paired with a
dictionary for either `subjectcontext`, `bodycontext`,
or `htmlcontext` to fill template with contextual
information.
"""
# Validate Path
if not path.endswith('.emlx'):
raise ValueError("Improper File Type: Must be *.emlx file.")
# Read Email Subject and Body
with open(path,'r') as emlx:
subj = emlx.readline()
x = emlx.readline() # Dummy Separator Line
body = ' '.join(emlx.readlines())
# Change Standard Text to HTML Formatting
if body.find('<html>') != -1:
html = body
body = ''
else:
html = ''
# Clean Text Strings
subj = subj.replace('\n','')
body = body.replace('\n','').replace(';;','\n')
html = html.replace(';;','<br>\n')
# Perform Formatting Operations
if isinstance(subjectcontext,dict):
for key,val in subjectcontext.items():
subj = subj.replace('{{'+str(key)+'}}', str(val))
if isinstance(bodycontext,dict):
for key,val in bodycontext.items():
body = body.replace('{{'+str(key)+'}}', str(val))
if isinstance(htmlcontext,dict):
for key,val in htmlcontext.items():
html = html.replace('{{'+str(key)+'}}', str(val))
return({'subject':subj,'body':body,'html':html})
# Define Builtin Test Aparatus
if __name__ == '__main__' :
recipients = [ '[email protected]',
files = "files/02-02-2020-20:46_autowatermanager.log"
# Evaluate Template
x=emailtemplate("/home/tech/BarnAuto/email/errnotice.emlx",
None,{'notice':'some test notice'})
# Send Email
send_email( recipients, x, files )
print("Success")
# END