-
Notifications
You must be signed in to change notification settings - Fork 0
/
emailService.py
247 lines (204 loc) · 6.62 KB
/
emailService.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
from smtplib import SMTP
from smtplib import SMTPException
from ssl import create_default_context
from threading import Thread
from typing import Optional
class EmailServiceSettings:
username: str
password: str
server: str
port: int
def __init__(self, username: str, password: str, server: str, port: int, dev_mode: bool = False) -> None:
self.dev_mode = dev_mode
self.username = username
self.password = password
self.server = server
self.port = port
class EmailService:
dev_mode: bool
username: str
password: str
server: str
port: int
_subject: str
_msg: Optional[MIMEMultipart]
_msg_body: Optional[MIMEText]
_original_sender: str
_reply_to: str
_from: str
_recipients: set[str]
_cc_recipients: set[str]
_bcc_recipients: set[str]
_attachments: set[tuple[Path, str]]
def __init__(self, settings: EmailServiceSettings) -> None:
self.dev_mode = settings.dev_mode
self.username = settings.username
self.password = settings.password
self.server = settings.server
self.port = settings.port
self._subject = ""
self._msg_body = MIMEText("")
self._original_msg_body = MIMEText("")
self._original_sender = settings.username
self._reply_to = settings.username
self._from = settings.username
self._recipients = set()
self._cc_recipients = set()
self._bcc_recipients = set()
self._attachments = set()
self._msg = MIMEMultipart()
self._msg.set_type("multipart/alternative")
def __repr__(self) -> str:
attachments = "\n".join(
[f"{file} - {status}" for file, status in self._attachments]
)
return (
f"<Class: EmailService>"
f"\n{self._msg}\n"
"Files set for attachment:\n"
f"{attachments}"
)
def subject(
self,
subject: str,
) -> "EmailService":
self._subject = subject
return self
def body(
self,
body: str,
) -> "EmailService":
self._original_msg_body = body
self._msg_body = MIMEText(body)
self._msg_body.set_type("text/html")
self._msg_body.set_param("charset", "UTF-8")
self._msg.attach(self._msg_body)
return self
def reply_to(self, reply_to: str) -> "EmailService":
self._msg.replace_header("Reply-To", reply_to)
return self
def from_(self, from_: str) -> "EmailService":
self._from = from_
return self
def recipients(self, recipients: list[str]) -> "EmailService":
self._recipients.update(set(recipients))
if "To" in self._msg:
self._msg.replace_header("To", ", ".join(self._recipients))
return self
self._msg.add_header("To", ", ".join(self._recipients))
return self
def cc_recipients(self, cc_recipients: list[str]) -> "EmailService":
self._cc_recipients.update(set(cc_recipients))
if "CC" in self._msg:
self._msg.replace_header("CC", ", ".join(self._cc_recipients))
return self
self._msg.add_header("CC", ", ".join(self._cc_recipients))
return self
def bcc_recipients(self, bcc_recipients: list[str]) -> "EmailService":
self._bcc_recipients.update(set(bcc_recipients))
if "BCC" in self._msg:
self._msg.replace_header("BCC", ", ".join(self._bcc_recipients))
return self
self._msg.add_header("BCC", ", ".join(self._bcc_recipients))
return self
def attach_files(self, files: list[str | Path]) -> "EmailService":
for file in files:
if isinstance(file, Path):
filepath: Path = file
else:
filepath: Path = Path(file)
self._attachments.update(
[(filepath, "Exists" if filepath.exists() else "Missing")]
)
if filepath.exists():
contents = MIMEApplication(
filepath.read_bytes(), _subtype=filepath.suffix
)
contents.add_header(
"Content-Disposition", "attachment", filename=filepath.name
)
self._msg.attach(contents)
return self
def attach_file(self, file: str | Path) -> "EmailService":
self.attach_files([file])
return self
def send(self, debug: bool = False) -> bool:
"""
Sends the email. If debug is True, it will print the email.
:param debug:
:return:
"""
self._msg.add_header("Original-Sender", self._original_sender)
self._msg.add_header("Reply-To", self._reply_to)
self._msg.add_header("From", self._from)
self._msg.add_header("Subject", self._subject)
if self.dev_mode:
print()
print("printing email:")
print(self)
print()
print("Original message:")
print(self._original_msg_body)
print()
return True
try:
with SMTP(self.server, self.port) as connection:
connection.starttls(context=create_default_context())
connection.login(self.username, self.password)
connection.sendmail(
self.username,
[*self._recipients, *self._cc_recipients, *self._bcc_recipients],
self._msg.as_string(),
)
except SMTPException as error:
if debug:
print(error)
return False
if debug:
print()
print("printing email after sending:")
print(self)
print()
print("Original message:")
print(self._original_msg_body)
print()
return True
# usage:
"""
email_service_settings = EmailServiceSettings(
username="[email protected]",
password="none",
server="none.none.none",
port=000
)
email_service = EmailService(
email_service_settings
)
email_service.adjust_from("Test 0 <[email protected]>")
email_service.recipients(
)
email_service.cc_recipients(
)
email_service.bcc_recipients(
)
email_service.subject(
"test"
)
email_service.body(
"test"
)
email_service.attach_files(
[
Path(Path.cwd() / "test1.txt"),
Path(Path.cwd() / "test2.txt")
]
)
email_service.send()
"""