forked from Chandan8186/cs3103-grp-30
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smtp_connection.py
62 lines (55 loc) · 1.89 KB
/
smtp_connection.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
from parser import *
import smtplib
class SMTP_Connection:
"""
SMTP_Connection class to encapsulate SMTP connection to mail server
Attributes:
host (str): Hostname of mail server
port (int): Port number to inform server to establish SMTP connection using SSL or TLS
user (str): Email address of user
password (str): User's password or Application password generated by user
Sample usage:
smtp_server = SMTP_Connection('smtp.gmail.com', 587, '<Your Email Address>', '<App Password Generated>')
smtp_server.connect()
...
<prepare email>
...
# Send message
smtp_server.send(<email crafted>)
"""
def __init__(self, host, port, user, password):
self.host = host
self.port = port
self.user = user
self.password = password
self.smtp = None
def connect(self):
"""
Establishes SMTP connection to given SMTP server.
"""
self.smtp = smtplib.SMTP(self.host, self.port)
if (self.port == 587):
self.smtp.starttls()
try:
self.smtp.login(self.user, self.password)
except Exception as err:
return f'Unable to connect or login into {self.host} due to the following reason:\n{str(err)}.'
return "Success"
def __del__(self):
"""
Disconnects SMTP connection with mail server
"""
if self.smtp:
self.smtp.quit()
def send_message(self, msg):
"""
Sends email to target recipient
Parameter:
msg (email.message.EmailMessage) : Email message containing the recipient, subject and body
Returns: (str): Error messages from sending email. Empty if successful.
"""
try:
self.smtp.send_message(msg)
return "✓"
except Exception as err:
return "Error: " + str(err)