-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail_handler.py
78 lines (60 loc) · 2.6 KB
/
email_handler.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
##------------------------------------------
##--- Author: Pradeep Singh
##--- Blog: https://iotbytes.wordpress.com/programmatically-send-e-mail-from-raspberry-pi-using-python-and-gmail/
##--- Date: 21st Feb 2017
##--- Version: 1.0
##--- Python Ver: 2.7
##--- Description: This python code will send Plain Text and HTML based emails using Gmail SMTP server
##--- Modified 31 October 2019 by Chip Fleming for Irrigation System Master Water Valve project
##------------------------------------------
import configparser, inspect, os
import smtplib
from email.mime.text import MIMEText
#Form the absolute path for the settings.ini file
settings_Dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
settings_File_Path = os.path.join(settings_Dir, 'settings.ini')
#================= GET SETTINGS FROM EMAIL SECTION IN settings.ini FILE ==============
def read_Email_Settings():
try:
config = configparser.ConfigParser()
config.optionxform=str #By default config returns keys from Settings file in lower case. This line preserves the case for keys
config.read(settings_File_Path)
global SMTP_SERVER
global SMTP_PORT
global FROM_ADD
global recipients
global TO_ADD
global CC_ADD
global USERNAME
global PASSWORD
SMTP_SERVER = config.get("EMAIL","SMTP_ADD")
SMTP_PORT = config.get("EMAIL","SMTP_PORT")
FROM_ADD = config.get("EMAIL","FROM_ADD")
TO_ADD = config.get("EMAIL","TO_ADD")
USERNAME = config.get("EMAIL","USERNAME")
PASSWORD = config.get("EMAIL","PASSWORD")
except Exception as error_msg:
print ("Error while trying to read SMTP/EMAIL Settings.")
print ("Error", str(error_msg))
#=====================================================================================
read_Email_Settings()
class Class_eMail():
def __init__(self):
self.session = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
self.session.ehlo()
self.session.login(USERNAME, PASSWORD)
def initialise_Mail_Body(self, Subject):
#Prepare Mail Body
Mail_Body = MIMEText()
Mail_Body['From'] = FROM_ADD
Mail_Body['To'] = TO_ADD
Mail_Body['Subject'] = Subject
return Mail_Body
#Call this to send plain text emails.
def send_Text_Mail(self, Subject, txtMessage):
Mail_Body = MIMEText(txtMessage)
#Send Mail
self.session.sendmail(FROM_ADD, TO_ADD, Mail_Body.as_string())
def __del__(self):
self.session.close()
del self.session