PyEmailerAJM 1.5.3__tar.gz → 1.6__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/PKG-INFO +13 -7
- pyemailerajm-1.6/PyEmailerAJM/__init__.py +8 -0
- pyemailerajm-1.6/PyEmailerAJM/_version.py +1 -0
- pyemailerajm-1.6/PyEmailerAJM/errs.py +6 -0
- pyemailerajm-1.6/PyEmailerAJM/helpers.py +40 -0
- pyemailerajm-1.6/PyEmailerAJM/msg.py +230 -0
- pyemailerajm-1.6/PyEmailerAJM/py_emailer_ajm.py +518 -0
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/PyEmailerAJM.egg-info/PKG-INFO +13 -7
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/PyEmailerAJM.egg-info/SOURCES.txt +7 -2
- pyemailerajm-1.6/setup.py +26 -0
- pyemailerajm-1.6/tests/test_PyEmailerAJM.py +128 -0
- PyEmailerAJM-1.5.3/PyEmailerAJM/PyEmailerAJM.py +0 -408
- PyEmailerAJM-1.5.3/PyEmailerAJM/__init__.py +0 -3
- PyEmailerAJM-1.5.3/setup.py +0 -15
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/LICENSE.txt +0 -0
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/PyEmailerAJM.egg-info/dependency_links.txt +0 -0
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/PyEmailerAJM.egg-info/requires.txt +0 -0
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/PyEmailerAJM.egg-info/top_level.txt +0 -0
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/README.md +0 -0
- {PyEmailerAJM-1.5.3 → pyemailerajm-1.6}/setup.cfg +0 -0
|
@@ -1,15 +1,21 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: PyEmailerAJM
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.6
|
|
4
4
|
Summary: Allows for automating sending Email with the Outlook Desktop client. Future releases will add more client support
|
|
5
5
|
Home-page: https://github.com/amcsparron2793-Water/PyEmailer
|
|
6
|
+
Download-URL: https://github.com/amcsparron2793-Water/PyEmailer/archive/refs/tags/1.6.tar.gz
|
|
6
7
|
Author: Amcsparron
|
|
7
8
|
Author-email: amcsparron@albanyny.gov
|
|
8
9
|
License: MIT License
|
|
9
|
-
Download-URL: https://github.com/amcsparron2793-Water/PyEmailer/archive/refs/tags/1.5.3.tar.gz
|
|
10
10
|
Keywords: Outlook,Email,Automation
|
|
11
|
-
Platform: UNKNOWN
|
|
12
11
|
License-File: LICENSE.txt
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
Requires-Dist: pywin32
|
|
13
|
+
Dynamic: author
|
|
14
|
+
Dynamic: author-email
|
|
15
|
+
Dynamic: download-url
|
|
16
|
+
Dynamic: home-page
|
|
17
|
+
Dynamic: keywords
|
|
18
|
+
Dynamic: license
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
Dynamic: requires-dist
|
|
21
|
+
Dynamic: summary
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from PyEmailerAJM.errs import EmailerNotSetupError, DisplayManualQuit
|
|
2
|
+
from PyEmailerAJM.helpers import deprecated, BasicEmailFolderChoices
|
|
3
|
+
from PyEmailerAJM.msg import Msg, FailedMsg
|
|
4
|
+
from PyEmailerAJM.py_emailer_ajm import PyEmailer, EmailerInitializer
|
|
5
|
+
|
|
6
|
+
__all__ = ['EmailerNotSetupError', 'DisplayManualQuit', 'deprecated',
|
|
7
|
+
'BasicEmailFolderChoices', 'Msg', 'FailedMsg',
|
|
8
|
+
'PyEmailer', 'EmailerInitializer']
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = '1.6'
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
import functools
|
|
3
|
+
from enum import IntEnum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BasicEmailFolderChoices(IntEnum):
|
|
7
|
+
INBOX = 6
|
|
8
|
+
SENT_ITEMS = 5
|
|
9
|
+
DRAFTS = 16
|
|
10
|
+
DELETED_ITEMS = 3
|
|
11
|
+
OUTBOX = 4
|
|
12
|
+
|
|
13
|
+
def __str__(self):
|
|
14
|
+
"""Return the enum name as a string."""
|
|
15
|
+
return self.name
|
|
16
|
+
|
|
17
|
+
def __repr__(self):
|
|
18
|
+
return f"<{self.__class__.__name__}.{self.name} ({self.value})>"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def deprecated(reason: str = ""):
|
|
22
|
+
"""
|
|
23
|
+
Decorator that marks a function or method as deprecated.
|
|
24
|
+
|
|
25
|
+
:param reason: Optional message to explain what to use instead
|
|
26
|
+
or when the feature will be removed.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def decorator(func):
|
|
30
|
+
@functools.wraps(func)
|
|
31
|
+
def wrapper(*args, **kwargs):
|
|
32
|
+
message = f"Function '{func.__name__}' is deprecated."
|
|
33
|
+
if reason:
|
|
34
|
+
message += f" {reason}"
|
|
35
|
+
warnings.warn(message, category=DeprecationWarning, stacklevel=2)
|
|
36
|
+
return func(*args, **kwargs)
|
|
37
|
+
|
|
38
|
+
return wrapper
|
|
39
|
+
|
|
40
|
+
return decorator
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
from abc import abstractmethod
|
|
2
|
+
from os.path import isfile, isabs, abspath, join
|
|
3
|
+
from tempfile import gettempdir
|
|
4
|
+
|
|
5
|
+
import win32com.client as win32
|
|
6
|
+
import datetime
|
|
7
|
+
import extract_msg
|
|
8
|
+
from bs4 import BeautifulSoup
|
|
9
|
+
from logging import Logger, getLogger, warning
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _BasicMsgProperties:
|
|
13
|
+
def __init__(self, email_item: win32.CDispatch):
|
|
14
|
+
self.email_item = email_item
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
@abstractmethod
|
|
18
|
+
def _validate_and_add_attachments(cls, email_item: win32.CDispatch, attachment_list: list = None):
|
|
19
|
+
...
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def sender(self):
|
|
23
|
+
if hasattr(self.email_item, 'SenderEmailType') and self.email_item.SenderEmailType == 'EX':
|
|
24
|
+
return self.email_item.Sender.GetExchangeUser().PrimarySmtpAddress
|
|
25
|
+
# return self.email_item.Sender if hasattr(self.email_item, 'Sender') else self.email_item.sender
|
|
26
|
+
else:
|
|
27
|
+
return self.email_item.SenderEmailAddress
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def sender_name(self):
|
|
31
|
+
return self.email_item.Sender if hasattr(self.email_item, 'Sender') else self.email_item.sender
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def to(self):
|
|
35
|
+
return self.email_item.To if hasattr(self.email_item, 'To') else self.email_item.to
|
|
36
|
+
|
|
37
|
+
def cc(self):
|
|
38
|
+
return self.email_item.CC if hasattr(self.email_item, 'CC') else self.email_item.cc
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def subject(self):
|
|
42
|
+
return self.email_item.Subject if hasattr(self.email_item, 'Subject') else self.email_item.subject
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def received_time(self):
|
|
46
|
+
#not_future = self.email_item.ReceivedTime.year < datetime.datetime.now().year
|
|
47
|
+
return self.email_item.ReceivedTime #if not_future else None
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def body(self):
|
|
51
|
+
return self.email_item.HTMLBody if hasattr(self.email_item, 'HTMLBody') else self.email_item.htmlBody
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def attachments(self):
|
|
55
|
+
return self.email_item.Attachments
|
|
56
|
+
|
|
57
|
+
@attachments.setter
|
|
58
|
+
def attachments(self, value: list):
|
|
59
|
+
self._validate_and_add_attachments(self.email_item, value)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Msg(_BasicMsgProperties):
|
|
63
|
+
def __init__(self, email_item: win32.CDispatch or extract_msg.Message, **kwargs):
|
|
64
|
+
super().__init__(email_item)
|
|
65
|
+
self._logger: Logger = kwargs.get('logger', getLogger(__name__))
|
|
66
|
+
self.send_success = False
|
|
67
|
+
|
|
68
|
+
def __call__(self, *args, **kwargs):
|
|
69
|
+
return self.email_item
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def SetupMsg(cls, sender, recipient, subject, body, email_item: win32.CDispatch, attachments: list = None, **kwargs):
|
|
73
|
+
email_item.To = recipient
|
|
74
|
+
email_item.Sender = sender
|
|
75
|
+
email_item.Subject = subject
|
|
76
|
+
email_item.HtmlBody = body
|
|
77
|
+
email_item.cc = kwargs.get('cc', '')
|
|
78
|
+
email_item.Bcc = kwargs.get('bcc', '')
|
|
79
|
+
|
|
80
|
+
cls._validate_and_add_attachments(email_item, attachments)
|
|
81
|
+
return cls(email_item, **kwargs)
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def _validate_and_add_attachments(cls, email_item: win32.CDispatch, attachment_list: list = None):
|
|
85
|
+
""" Validate and attach files to the email_item. """
|
|
86
|
+
if not attachment_list:
|
|
87
|
+
warning("No attachments detected")
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
if not isinstance(attachment_list, list):
|
|
91
|
+
raise TypeError("Attachments must be provided as a list")
|
|
92
|
+
|
|
93
|
+
def _absolute_file_path(file_path):
|
|
94
|
+
"""Returns absolute path if valid; raises FileNotFoundError otherwise."""
|
|
95
|
+
if not isabs(file_path):
|
|
96
|
+
file_path = abspath(file_path)
|
|
97
|
+
if not isfile(file_path):
|
|
98
|
+
raise FileNotFoundError(f"File {file_path} could not be attached.")
|
|
99
|
+
return file_path
|
|
100
|
+
|
|
101
|
+
for attachment in attachment_list:
|
|
102
|
+
email_item.attachments.Add(_absolute_file_path(attachment))
|
|
103
|
+
|
|
104
|
+
def SaveAllEmailAttachments(self, save_dir_path):
|
|
105
|
+
all_attachment_paths = set()
|
|
106
|
+
for attachment in self.attachments:
|
|
107
|
+
full_save_path = join(save_dir_path, str(attachment))
|
|
108
|
+
try:
|
|
109
|
+
attachment.SaveAsFile(full_save_path)
|
|
110
|
+
all_attachment_paths.add(full_save_path)
|
|
111
|
+
self._logger.debug(f"{full_save_path} saved from email with subject {self.subject}")
|
|
112
|
+
except Exception as e:
|
|
113
|
+
self._logger.error(e, exc_info=True)
|
|
114
|
+
raise e
|
|
115
|
+
return all_attachment_paths
|
|
116
|
+
|
|
117
|
+
def display(self):
|
|
118
|
+
# print(f"Displaying the email in {self.email_app_name}, this window might open minimized.")
|
|
119
|
+
# self._logger.info(f"Displaying the email in {self.email_app_name}, this window might open minimized.")
|
|
120
|
+
try:
|
|
121
|
+
self().Display(True)
|
|
122
|
+
except Exception as e:
|
|
123
|
+
self._logger.error(e, exc_info=True)
|
|
124
|
+
raise e
|
|
125
|
+
|
|
126
|
+
def send(self):
|
|
127
|
+
try:
|
|
128
|
+
# if the send fails, self.to is NULL, so this needs to be saved in a local variable
|
|
129
|
+
attempted_recipient = self.to
|
|
130
|
+
self.send_success = False
|
|
131
|
+
self().Send()
|
|
132
|
+
# print(f"Mail sent to {self._recipient}")
|
|
133
|
+
self.send_success = True
|
|
134
|
+
self._logger.info(f"Mail successfully sent to {attempted_recipient}")
|
|
135
|
+
except Exception as e:
|
|
136
|
+
self._logger.error(e, exc_info=True)
|
|
137
|
+
raise e
|
|
138
|
+
|
|
139
|
+
def _ValidateResponseMsg(self):
|
|
140
|
+
if isinstance(self(), win32.CDispatch):
|
|
141
|
+
self._logger.debug("passed in msg is CDispatch instance")
|
|
142
|
+
if hasattr(self(), 'HtmlBody') or hasattr(self(), 'htmlBody'):
|
|
143
|
+
self._logger.debug("passed in msg has 'HtmlBody' or 'htmlBody' attr")
|
|
144
|
+
|
|
145
|
+
if (not isinstance(self(), win32.CDispatch)
|
|
146
|
+
or not hasattr(self(), ('HtmlBody' or 'htmlBody'))):
|
|
147
|
+
raise AttributeError("msg attr must have 'HtmlBody' attr AND be a CDispatch instance")
|
|
148
|
+
return self()
|
|
149
|
+
|
|
150
|
+
def _msg_is_recent(self, recent_days_cap=1):
|
|
151
|
+
if self.received_time is not None:
|
|
152
|
+
abs_diff = abs(self.received_time - datetime.datetime.now(tz=self.received_time.tzinfo))
|
|
153
|
+
return abs_diff <= datetime.timedelta(days=recent_days_cap)
|
|
154
|
+
print(f"msg with subject \'{self.email_item.Subject}\' has no received time. defaulting to false")
|
|
155
|
+
self._logger.debug(f"msg with subject \'{self.email_item.Subject}\' has no received time. defaulting to false")
|
|
156
|
+
return False
|
|
157
|
+
|
|
158
|
+
def return_as_failed_send(self):
|
|
159
|
+
return FailedMsg(self())
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class FailedMsg(Msg):
|
|
163
|
+
ERR_SKIP_STRING = "err {}: skipping this message"
|
|
164
|
+
DEFAULT_TEMP_SAVE_PATH = gettempdir()
|
|
165
|
+
|
|
166
|
+
def _message_filter_checks(self, **kwargs) -> bool:
|
|
167
|
+
recent_days_cap = kwargs.get('recent_days_cap', 1)
|
|
168
|
+
return self._msg_is_recent(recent_days_cap)
|
|
169
|
+
|
|
170
|
+
def _fetch_failed_msg_details(self, **kwargs):
|
|
171
|
+
temp_attachment_save_path = kwargs.get('temp_attachment_save_path',
|
|
172
|
+
self.__class__.DEFAULT_TEMP_SAVE_PATH)
|
|
173
|
+
try:
|
|
174
|
+
attachment_msg_path = self.SaveAllEmailAttachments(temp_attachment_save_path)
|
|
175
|
+
print('saved_attachments')
|
|
176
|
+
except Exception as e:
|
|
177
|
+
self._logger.warning(self.__class__.ERR_SKIP_STRING.format(f'({e})'))
|
|
178
|
+
return e
|
|
179
|
+
if len(attachment_msg_path) == 1:
|
|
180
|
+
return next(iter(attachment_msg_path))
|
|
181
|
+
return attachment_msg_path
|
|
182
|
+
|
|
183
|
+
def process_failed_msg(self, post_master_msg, **kwargs):
|
|
184
|
+
recent_days_cap = kwargs.get('recent_days_cap', 1)
|
|
185
|
+
try:
|
|
186
|
+
self.email_item = post_master_msg
|
|
187
|
+
self._ValidateResponseMsg()
|
|
188
|
+
except AttributeError as e:
|
|
189
|
+
self._logger.warning(self.__class__.ERR_SKIP_STRING.format(f'({e})'))
|
|
190
|
+
return e, None, None
|
|
191
|
+
|
|
192
|
+
if self._msg_is_recent(recent_days_cap):
|
|
193
|
+
attachment_msg = self._fetch_failed_msg_details()
|
|
194
|
+
if isinstance(attachment_msg, Exception):
|
|
195
|
+
return attachment_msg, None, None
|
|
196
|
+
else:
|
|
197
|
+
if isinstance(attachment_msg, str):
|
|
198
|
+
fmd = _FailedMessageDetails.extract_msg_from_attachment(attachment_msg)
|
|
199
|
+
return fmd.process_failed_details_msg() #self._process_failed_details_msg(attachment_msg)
|
|
200
|
+
return None, None, None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class _FailedMessageDetails(FailedMsg):
|
|
204
|
+
@classmethod
|
|
205
|
+
def extract_msg_from_attachment(cls, parent_msg: str):
|
|
206
|
+
return cls(extract_msg.Message(parent_msg))
|
|
207
|
+
|
|
208
|
+
def _extract_from_failed_details_msg(self, para):
|
|
209
|
+
email_of_err = para.findNext('p').get_text().strip().split('(')[0].strip()
|
|
210
|
+
err_reason = para.findNext('p').findNext('p').get_text()
|
|
211
|
+
send_time = self().date.ctime()
|
|
212
|
+
failed_subject = self.subject
|
|
213
|
+
|
|
214
|
+
err_details = {'email_of_err': email_of_err, 'err_reason': err_reason,
|
|
215
|
+
'send_time': send_time, 'failed_subject': failed_subject}
|
|
216
|
+
# print(f"Email of err: {email_of_err},\nErr reason: {err_reason}\nSend time: {send_time}")
|
|
217
|
+
return err_details #email_of_err, err_reason, send_time
|
|
218
|
+
|
|
219
|
+
def process_failed_details_msg(self, **kwargs):
|
|
220
|
+
detail_marker_string = kwargs.get('detail_marker_string',
|
|
221
|
+
"Delivery has failed to these recipients or groups:")
|
|
222
|
+
|
|
223
|
+
soup = BeautifulSoup(self.body, features="html.parser")
|
|
224
|
+
|
|
225
|
+
all_p = soup.find_all(name='p') # , attrs={'class': 'MsoNormal'})
|
|
226
|
+
|
|
227
|
+
for para in all_p:
|
|
228
|
+
if detail_marker_string in para.get_text():
|
|
229
|
+
return {** self._extract_from_failed_details_msg(para)}
|
|
230
|
+
return None, None, None
|