forked from kz26/mailproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser_handlers.py
208 lines (176 loc) · 6.32 KB
/
user_handlers.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import configparser
import smtplib
import imaplib
from time import time
from typing import List
import logging
import logging.config
logging.config.fileConfig('logging.conf', disable_existing_loggers=False)
logger = logging.getLogger('main')
class SmtpHandler:
"""Smtp handler"""
def __init__(
self,
host: str,
port: int,
user: str,
password: str,
use_ssl: bool = False,
start_tls: bool = False,
):
"""
@param host:
@param port:
@param user:
@param password:
@param use_ssl:
@param start_tls:
"""
self._host = host
self._port = port
self._user = user
self._password = password
self._use_ssl = use_ssl
self._start_tls = start_tls
@staticmethod
def load_smtp(config: configparser.ConfigParser, email: str):
"""
Load smtp handler.
@param config: config data to load
@param email: email to load
@return: SmtpHandler class
"""
key_value = f"smtp_{email}"
try:
host = config.get(key_value, "host")
port = config.getint(key_value, "port")
# user - not need ?
password = config.get(key_value, "password")
use_ssl = config.getboolean(key_value, "use_ssl")
start_tls = config.getboolean(key_value, "start_tls")
return SmtpHandler(host, port, email, password, use_ssl, start_tls)
except ValueError as e:
logger.error(f"Invalid value found for a variable {e}.")
except configparser.NoOptionError as e:
logger.error(f"No option {e.option} found in section {e.section}.")
except configparser.NoSectionError as e:
logger.error(f"Section {e.section} not found.")
except configparser.ParsingError:
logger.error("Error while parsing the configuration file.")
return None
def send_email(self, rcpt_tos: List[str], original_content: bytes):
"""
@param rcpt_tos: list emails to receive emails.
@param original_content: letter content
@return:
"""
# TODO test session place in self context?
if self._use_ssl:
session = smtplib.SMTP_SSL(self._host, self._port)
else:
session = smtplib.SMTP(self._host, self._port)
if self._start_tls:
session.starttls()
session.ehlo()
if self._user and self._password:
session.login(self._user, self._password)
refused_recipients = {}
try:
# TODO check before call
refused_recipients = session.sendmail(
self._user, rcpt_tos, original_content
)
return "250 Message accepted for delivery"
except smtplib.SMTPRecipientsRefused:
logger.error(
f"Recipients refused: {' '.join(refused_recipients.keys())}")
return f'553 Recipients refused {"".join(refused_recipients.keys())}'
except smtplib.SMTPResponseException as e:
logger.error(
f"SMTP response exception: {e.smtp_code} {e.smtp_error}")
return f"{e.smtp_code} {e.smtp_error}"
except Exception as e:
logger.error(
f"Exception while implementing email using SMTP: {str(e)}")
finally:
session.quit()
class ImapHandler:
"""Параметры для авторизации Imap"""
def __init__(
self,
host: str,
port: int,
user: str,
password: str,
use_ssl: bool = False,
folder="Sent",
):
"""
@param host:
@param port:
@param user:
@param password:
@param use_ssl:
@param folder:
"""
self._host = host
self._port = port
self._user = user
self._password = password
self._use_ssl = use_ssl
self._folder = folder
@staticmethod
def load_imap(config: configparser.ConfigParser, email: str):
"""Load imap from config"""
key_value = f"imap_{email}"
try:
host = config.get(key_value, "host")
port = config.getint(key_value, "port")
password = config.get(key_value, "password")
use_ssl = config.getboolean(key_value, "use_ssl")
folder = config.get(key_value, "folder").strip()
return ImapHandler(host, port, email, password, use_ssl, folder)
except ValueError as e:
logger.error(f"Invalid value found for a variable {e}.")
except configparser.NoOptionError as e:
logger.error(f"No option {e.option} found in section {e.section}.")
except configparser.NoSectionError as e:
logger.error(f"Section {e.section} not found.")
except configparser.ParsingError:
logger.error("Error while parsing the configuration file.")
except Exception as e:
logger.error(
f"Exception while implementing email using IMAP: {str(e)}")
return None
def store_email(self, original_content: bytes):
# TODO test session place in self context?
if self._use_ssl:
session = imaplib.IMAP4_SSL(self._host, self._port)
else:
session = imaplib.IMAP4(self._host, self._port)
try:
session.login(self._user, self._password)
except Exception as e:
logger.error(
f"Exception while login email using IMAP: {str(e)}")
value = original_content
try:
session.append(self._folder, "",
imaplib.Time2Internaldate(time()), value)
except Exception as e:
logger.error(
f"Exception while append email using IMAP: {str(e)}")
finally:
session.logout()
class MailUser:
def __init__(
self, login: str, smtp_handler: SmtpHandler,
imap_handler: ImapHandler
):
self.login = login
self.smtp_handler = smtp_handler
self.imap_handler = imap_handler
def __eq__(self, value):
return isinstance(value, self.__class__) and self.login == value.login
def __hash__(self):
return hash(self.login)