cjnfuncs 2.2__tar.gz → 2.4__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.
- {cjnfuncs-2.2/src/cjnfuncs.egg-info → cjnfuncs-2.4}/PKG-INFO +7 -2
- {cjnfuncs-2.2 → cjnfuncs-2.4}/README.md +6 -1
- {cjnfuncs-2.2 → cjnfuncs-2.4}/pyproject.toml +9 -2
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/SMTP.py +202 -71
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/configman.py +43 -36
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/core.py +9 -9
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/deployfiles.py +4 -4
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/mungePath.py +47 -37
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/resourcelock.py +140 -29
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/timevalue.py +6 -6
- {cjnfuncs-2.2 → cjnfuncs-2.4/src/cjnfuncs.egg-info}/PKG-INFO +7 -2
- {cjnfuncs-2.2 → cjnfuncs-2.4}/LICENSE.txt +0 -0
- {cjnfuncs-2.2 → cjnfuncs-2.4}/setup.cfg +0 -0
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs/__init__.py +0 -0
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs.egg-info/SOURCES.txt +0 -0
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs.egg-info/dependency_links.txt +0 -0
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs.egg-info/entry_points.txt +0 -0
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs.egg-info/requires.txt +0 -0
- {cjnfuncs-2.2 → cjnfuncs-2.4}/src/cjnfuncs.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: cjnfuncs
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.4
|
|
4
4
|
Summary: A collection of core functions for tool script writing
|
|
5
5
|
Author-email: Chris Nelson <github@cjnaz.com>
|
|
6
6
|
License: MIT License
|
|
@@ -37,7 +37,7 @@ Requires-Dist: posix-ipc>=1.1.1
|
|
|
37
37
|
|
|
38
38
|
# cjnfuncs - A framework and collection of utility functions for script writing
|
|
39
39
|
|
|
40
|
-
## cjnfuncs is comprised of several modules (links to respective documentation)
|
|
40
|
+
## cjnfuncs is comprised of several modules (follow links to respective documentation)
|
|
41
41
|
|
|
42
42
|
NOTE: Since relative links to other .md files do not work on PyPI, please go to the [cjnfuncs GitHub repo](https://github.com/cjnaz/cjnfuncs) to read the documentation.
|
|
43
43
|
|
|
@@ -75,6 +75,11 @@ Project repo: https://github.com/cjnaz/cjnfuncs
|
|
|
75
75
|
<br/>
|
|
76
76
|
|
|
77
77
|
## Revision history
|
|
78
|
+
- 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
|
|
79
|
+
- 2.3 240821 - Added mungePath ./ support.
|
|
80
|
+
Resolved check_path_exists() memory leak.
|
|
81
|
+
Added `same_process_ok` to resourcelock.getlock()
|
|
82
|
+
Added prereload_callback to config_item.loadconfig()
|
|
78
83
|
- 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
|
|
79
84
|
- 2.1 240104 - Partitioned to separate modules.
|
|
80
85
|
Added modify_configfile.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# cjnfuncs - A framework and collection of utility functions for script writing
|
|
2
2
|
|
|
3
|
-
## cjnfuncs is comprised of several modules (links to respective documentation)
|
|
3
|
+
## cjnfuncs is comprised of several modules (follow links to respective documentation)
|
|
4
4
|
|
|
5
5
|
NOTE: Since relative links to other .md files do not work on PyPI, please go to the [cjnfuncs GitHub repo](https://github.com/cjnaz/cjnfuncs) to read the documentation.
|
|
6
6
|
|
|
@@ -38,6 +38,11 @@ Project repo: https://github.com/cjnaz/cjnfuncs
|
|
|
38
38
|
<br/>
|
|
39
39
|
|
|
40
40
|
## Revision history
|
|
41
|
+
- 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
|
|
42
|
+
- 2.3 240821 - Added mungePath ./ support.
|
|
43
|
+
Resolved check_path_exists() memory leak.
|
|
44
|
+
Added `same_process_ok` to resourcelock.getlock()
|
|
45
|
+
Added prereload_callback to config_item.loadconfig()
|
|
41
46
|
- 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
|
|
42
47
|
- 2.1 240104 - Partitioned to separate modules.
|
|
43
48
|
Added modify_configfile.
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["setuptools"]
|
|
2
|
+
requires = ["setuptools"]
|
|
3
3
|
build-backend = "setuptools.build_meta"
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
[project]
|
|
7
7
|
name = "cjnfuncs"
|
|
8
|
-
version = "2.
|
|
8
|
+
version = "2.4"
|
|
9
|
+
# 2.4 - release
|
|
10
|
+
# 2.4rc2 - check_path_exists() exception fix for unmounted network path (OSError: [Errno 19] No such device)
|
|
11
|
+
# 2.4rc1 - doc fix on setuplogging()
|
|
12
|
+
# 2.4b4 - resourcelock closed attribute
|
|
13
|
+
# 2.4b3 - Added lock_info to resource_lock
|
|
14
|
+
# 2.4b2 - Added where_called to resource_lock unget for debugging aid
|
|
15
|
+
# 2.4b1 - Added Twilio support to snd_notif
|
|
9
16
|
description = "A collection of core functions for tool script writing"
|
|
10
17
|
readme = "README.md"
|
|
11
18
|
requires-python = ">=3.6" # Centos 7 uses 3.6.8
|
|
@@ -4,11 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
#==========================================================
|
|
6
6
|
#
|
|
7
|
-
# Chris Nelson, 2018-
|
|
7
|
+
# Chris Nelson, 2018-2024
|
|
8
8
|
#
|
|
9
9
|
#==========================================================
|
|
10
10
|
|
|
11
11
|
import time
|
|
12
|
+
import sys
|
|
13
|
+
import importlib
|
|
14
|
+
import re
|
|
12
15
|
import smtplib
|
|
13
16
|
from email.mime.text import MIMEText
|
|
14
17
|
from email.utils import formatdate
|
|
@@ -16,13 +19,17 @@ from pathlib import Path
|
|
|
16
19
|
import dkim
|
|
17
20
|
|
|
18
21
|
from .core import logging, SndEmailError
|
|
19
|
-
from .mungePath import mungePath
|
|
22
|
+
from .mungePath import mungePath, check_path_exists
|
|
20
23
|
from .timevalue import timevalue
|
|
21
24
|
import cjnfuncs.core as core
|
|
22
25
|
|
|
23
26
|
# Configs / Constants
|
|
24
|
-
SND_EMAIL_NTRIES
|
|
25
|
-
|
|
27
|
+
SND_EMAIL_NTRIES = 3 # Number of tries to send email before aborting
|
|
28
|
+
RETRY_WAIT = '2s' # seconds between retries
|
|
29
|
+
SERVER_TIMEOUT = '2s' # server connection timeout
|
|
30
|
+
|
|
31
|
+
COUNTRY_CODE = 1 # US/Canada
|
|
32
|
+
PHONE_NUM_LENGTH = 10 # US/Canada
|
|
26
33
|
|
|
27
34
|
|
|
28
35
|
#=====================================================================================
|
|
@@ -31,11 +38,11 @@ SND_EMAIL_WAIT = '2s' # seconds between retries, and server connec
|
|
|
31
38
|
#=====================================================================================
|
|
32
39
|
#=====================================================================================
|
|
33
40
|
|
|
34
|
-
def snd_notif(subj='Notification message', msg='', to='NotifList', log=False, smtp_config=None):
|
|
41
|
+
def snd_notif(subj='Notification message', msg='', urls_list=[], to='NotifList', log=False, smtp_config=None):
|
|
35
42
|
"""
|
|
36
|
-
## snd_notif (subj='Notification message', msg='
|
|
43
|
+
## snd_notif (subj='Notification message', msg='', urls_list=[], to='NotifList', log=False, smtp_config=None) - Send a text message using info from the config file
|
|
37
44
|
|
|
38
|
-
Intended for use
|
|
45
|
+
Intended for use the mobile provider's (carrier's) email-to-SMS gateway email address, eg,
|
|
39
46
|
`5405551212@vzwtxt.com` for Verizon, but any email address will work.
|
|
40
47
|
|
|
41
48
|
The `to` string may be the name of a config param (who's value is one or more email addresses, default
|
|
@@ -47,40 +54,58 @@ Three attempts are made to send the message.
|
|
|
47
54
|
|
|
48
55
|
|
|
49
56
|
### Parameters
|
|
50
|
-
`subj` (default 'Notification message')
|
|
57
|
+
`subj` (str, default 'Notification message')
|
|
51
58
|
- Text message subject field
|
|
52
59
|
- Some SMS/MMS apps display the subj field in bold, some in raw form, and some not at all.
|
|
53
60
|
|
|
54
|
-
`msg` (default '
|
|
61
|
+
`msg` (str, default '')
|
|
55
62
|
- Text message body
|
|
56
63
|
|
|
57
|
-
`
|
|
64
|
+
`urls_list` (list, default [])
|
|
65
|
+
- A list of url strings to be passed to the message sending plugin module, which should pass them to the messaging service.
|
|
66
|
+
- This list is discarded by `snd_notif()` if not using a messaging service. If you want to send a message with
|
|
67
|
+
urls then included them in the `msg` body text.
|
|
68
|
+
|
|
69
|
+
`to` (str, default 'NotifList')
|
|
58
70
|
- To whom to send the message. `to` may be either an explicit string list of email addresses
|
|
59
71
|
(whitespace or comma separated) or a config param name (also listing one
|
|
60
72
|
or more whitespace or comma separated email addresses). If the `to` parameter does not
|
|
61
73
|
contain an '@' it is assumed to be a config param.
|
|
62
74
|
- Define `NotifList` in the config file to use the default `to` value.
|
|
63
75
|
|
|
64
|
-
`log` (default False)
|
|
76
|
+
`log` (bool, default False)
|
|
65
77
|
- If True, logs that the message was sent at the WARNING level. If False, logs
|
|
66
78
|
at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
|
|
67
79
|
The `subj` field is part of the log message.
|
|
68
80
|
|
|
69
|
-
`smtp_config` (
|
|
81
|
+
`smtp_config` (config_item class instance)
|
|
70
82
|
- config_item class instance containing the [SMTP] section and related params
|
|
71
83
|
|
|
72
84
|
|
|
73
|
-
###
|
|
85
|
+
### config dictionary params in the [SMTP] section, in addition to the config dictionary params required for snd_email
|
|
74
86
|
`NotifList` (optional)
|
|
75
87
|
- string list of email addresses (whitespace or comma separated).
|
|
76
88
|
- Defining `NotifList` in the config is only required if any call to `snd_notif()` uses this
|
|
77
89
|
default `to` parameter value.
|
|
78
90
|
|
|
79
91
|
`DontNotif` (default False)
|
|
80
|
-
- If True, notification messages are not sent. Useful for debug.
|
|
81
|
-
|
|
92
|
+
- If True, notification messages are not sent. `log` is still honored. Useful for debug.
|
|
93
|
+
- Setting `DontEmail` True also blocks sending notification messages if using a carrier email-to-SMS gateway
|
|
94
|
+
(not using a messaging service). If using a messaging service then `DontEmail` has no effect.
|
|
95
|
+
|
|
96
|
+
`Msg_Handler` (str, absolute path or package.module, default None)
|
|
97
|
+
- If using a messaging service, such as Twilio, this param declares the path to the message sending plugin module.
|
|
98
|
+
- The module must implement a `sender()` function, which will be called with a `package` dictionary containing `subj`, `msg`, `urls`, and `to` key:value pairs, and
|
|
99
|
+
a reference to the `smtp_config`. See the [SMTP.md](https://github.com/cjnaz/cjnfuncs/blob/main/SMTP.md) for an example Msg_Handler module implementation.
|
|
100
|
+
- `Msg_Handler` may be a full absolute path to a Python module (eg, `/path-to-module/twilioSender.py`), or an installed package.module reference (eg, `mypackage.twilioSender`).
|
|
82
101
|
|
|
102
|
+
`country_code` (int or str, default 1 (US/Canada), required only if `Msg_Handler` is defined in the config [SMTP] section)
|
|
103
|
+
- Number without a preceding '+', eg '1' for US/Canada phone numbers
|
|
104
|
+
- If `get_type='numbers'` then each phone number is prepended with `+` plus `country_code` (eg, '+1'), but only if the number does not already have a country code.
|
|
105
|
+
- If a `to` phone number has a different country code, it is retained.
|
|
83
106
|
|
|
107
|
+
`number_length` (int, default 10 (US/Canada), required only if `Msg_Handler` is defined in the config [SMTP] section)
|
|
108
|
+
- The number of digits in a valid phone number (not including the country code), eg 10 for US/Canada phone numbers
|
|
84
109
|
|
|
85
110
|
|
|
86
111
|
### Returns
|
|
@@ -92,22 +117,54 @@ messages are also blocked if `DontEmail` is True.
|
|
|
92
117
|
- `snd_notif()` uses `snd_email()` to send the message. See `snd_email()` for related setup.
|
|
93
118
|
"""
|
|
94
119
|
|
|
95
|
-
if smtp_config.getcfg('DontNotif', fallback=False, section='SMTP')
|
|
120
|
+
if smtp_config.getcfg('DontNotif', fallback=False, section='SMTP'):
|
|
96
121
|
if log:
|
|
97
122
|
logging.warning (f"Notification NOT sent <{subj}> <{msg}>")
|
|
98
123
|
else:
|
|
99
124
|
logging.debug (f"Notification NOT sent <{subj}> <{msg}>")
|
|
100
125
|
return
|
|
101
126
|
|
|
102
|
-
|
|
127
|
+
msg_handler = smtp_config.getcfg('Msg_Handler', fallback=None, section='SMTP')
|
|
128
|
+
|
|
129
|
+
if msg_handler:
|
|
130
|
+
# Import the messaging service handler
|
|
131
|
+
if msg_handler.startswith('/'): # Absolute path case
|
|
132
|
+
if not check_path_exists(msg_handler):
|
|
133
|
+
raise FileNotFoundError (f"Can't find SMS/MMS message handler <{msg_handler}>")
|
|
134
|
+
if msg_handler.endswith('.py'):
|
|
135
|
+
msg_handler = msg_handler[:-3]
|
|
136
|
+
xx = mungePath(msg_handler)
|
|
137
|
+
xx_parent = str(xx.parent)
|
|
138
|
+
if xx_parent not in sys.path:
|
|
139
|
+
sys.path.append(xx_parent)
|
|
140
|
+
try:
|
|
141
|
+
logging.info (xx)
|
|
142
|
+
sender_plugin = __import__(xx.name)
|
|
143
|
+
except Exception as e:
|
|
144
|
+
raise ImportError (f"Can't import SMS/MMS message handler <{msg_handler}>\n {e}")
|
|
145
|
+
logging.debug (f"Imported message sender plugin <{msg_handler}>, version <{sender_plugin.__version__}>")
|
|
146
|
+
else: # package.module case
|
|
147
|
+
try:
|
|
148
|
+
sender_plugin = importlib.import_module(msg_handler)
|
|
149
|
+
except Exception as e:
|
|
150
|
+
raise ImportError (f"Can't import SMS/MMS message handler <{msg_handler}>\n {e}")
|
|
151
|
+
logging.debug (f"Imported message sender plugin <{sender_plugin.__name__}>, version <{sender_plugin.__version__}>")
|
|
152
|
+
|
|
153
|
+
package = {'subj': subj,
|
|
154
|
+
'msg': msg,
|
|
155
|
+
'urls': urls_list,
|
|
156
|
+
'to': list_to(to, 'numbers', subj=subj, smtp_config=smtp_config) }
|
|
157
|
+
|
|
158
|
+
sender_plugin.sender(package, smtp_config)
|
|
159
|
+
|
|
160
|
+
else:
|
|
103
161
|
snd_email (subj=subj, body=msg, to=to, smtp_config=smtp_config)
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
logging.
|
|
110
|
-
raise e
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if log:
|
|
165
|
+
logging.warning (f"Notification sent <{subj}> <{msg}>")
|
|
166
|
+
else:
|
|
167
|
+
logging.debug (f"Notification sent <{subj}> <{msg}>")
|
|
111
168
|
|
|
112
169
|
|
|
113
170
|
#=====================================================================================
|
|
@@ -133,34 +190,34 @@ Three attempts are made to send the message (see `EmailNTries`, below).
|
|
|
133
190
|
|
|
134
191
|
|
|
135
192
|
### Parameters
|
|
136
|
-
`subj`
|
|
193
|
+
`subj` (str)
|
|
137
194
|
- Email subject text
|
|
138
195
|
|
|
139
|
-
`to`
|
|
196
|
+
`to` (str)
|
|
140
197
|
- To whom to send the message. `to` may be either an explicit string list of email addresses
|
|
141
198
|
(whitespace or comma separated) or a config param name in the [SMTP] section (also listing one
|
|
142
199
|
or more whitespace or comma separated email addresses). If the `to` parameter does not
|
|
143
200
|
contain an '@' it is assumed to be a config param.
|
|
144
201
|
|
|
145
|
-
`body` (default None)
|
|
202
|
+
`body` (str, default None)
|
|
146
203
|
- A string message to be sent
|
|
147
204
|
|
|
148
|
-
`filename` (default None)
|
|
205
|
+
`filename` (str, default None)
|
|
149
206
|
- A str or Path to the file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
|
|
150
207
|
|
|
151
|
-
`htmlfile` (default None)
|
|
208
|
+
`htmlfile` (str, default None)
|
|
152
209
|
- A str or Path to the html formatted file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
|
|
153
210
|
|
|
154
|
-
`log` (default False)
|
|
211
|
+
`log` (bool, default False)
|
|
155
212
|
- If True, logs that the message was sent at the WARNING level. If False, logs
|
|
156
213
|
at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
|
|
157
214
|
The `subj` field is part of the log message.
|
|
158
215
|
|
|
159
|
-
`smtp_config` (
|
|
216
|
+
`smtp_config` (config_item class instance)
|
|
160
217
|
- config_item class instance containing the [SMTP] section and related params
|
|
161
218
|
|
|
162
219
|
|
|
163
|
-
###
|
|
220
|
+
### config dictionary params in the [SMTP] section
|
|
164
221
|
`EmailFrom`
|
|
165
222
|
- An email address, such as `me@myserver.com`
|
|
166
223
|
|
|
@@ -187,7 +244,9 @@ The `subj` field is part of the log message.
|
|
|
187
244
|
|
|
188
245
|
`EmailRetryWait` (seconds, type int, float, or timevalue, default 2s)
|
|
189
246
|
- Number of seconds to wait between retry attempts
|
|
190
|
-
|
|
247
|
+
|
|
248
|
+
`EmailServerTimeout` (seconds, type int, float, or timevalue, default 2s)
|
|
249
|
+
- Server connection timeout
|
|
191
250
|
|
|
192
251
|
`EmailDKIMDomain` (required if using DKIM email signing)
|
|
193
252
|
- The domain of the public-facing SMTP server, eg `mydomain.com`
|
|
@@ -257,31 +316,12 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
|
|
|
257
316
|
m_text += f"\n(sent {time.asctime(time.localtime())})"
|
|
258
317
|
|
|
259
318
|
# Deal with 'to'
|
|
260
|
-
|
|
261
|
-
"""Return list of email addresses from comma or whitespace separated string 'addresses'.
|
|
262
|
-
"""
|
|
263
|
-
if ',' in addresses:
|
|
264
|
-
tmp = addresses.split(',')
|
|
265
|
-
addrs = []
|
|
266
|
-
for addr in tmp:
|
|
267
|
-
addrs.append(addr.strip())
|
|
268
|
-
else:
|
|
269
|
-
addrs = addresses.split()
|
|
270
|
-
return addrs
|
|
271
|
-
|
|
272
|
-
if '@' in to:
|
|
273
|
-
To = extract_email_addresses(to)
|
|
274
|
-
else:
|
|
275
|
-
To = extract_email_addresses(smtp_config.getcfg(to, "", section='SMTP'))
|
|
276
|
-
if len(To) == 0:
|
|
277
|
-
raise SndEmailError (f"snd_email - Message subject <{subj}>: 'to' list must not be empty.")
|
|
278
|
-
for address in To:
|
|
279
|
-
if '@' not in address:
|
|
280
|
-
raise SndEmailError (f"snd_email - Message subject <{subj}>: address in 'to' list is invalid: <{address}>.")
|
|
319
|
+
To = list_to(to, 'emails', subj, smtp_config=smtp_config)
|
|
281
320
|
|
|
282
321
|
# Gather, check remaining config params
|
|
283
322
|
ntries = smtp_config.getcfg('EmailNTries', SND_EMAIL_NTRIES, types=int, section='SMTP')
|
|
284
|
-
retry_wait = timevalue(smtp_config.getcfg('EmailRetryWait',
|
|
323
|
+
retry_wait = timevalue(smtp_config.getcfg('EmailRetryWait', RETRY_WAIT, types=[int, float, str], section='SMTP')).seconds
|
|
324
|
+
server_timeout = timevalue(smtp_config.getcfg('EmailServerTimeout', SERVER_TIMEOUT, types=[int, float, str], section='SMTP')).seconds
|
|
285
325
|
email_from = smtp_config.getcfg('EmailFrom', types=str, section='SMTP')
|
|
286
326
|
cfg_server = smtp_config.getcfg('EmailServer', types=str, section='SMTP')
|
|
287
327
|
cfg_port = smtp_config.getcfg('EmailServerPort', types=str, section='SMTP').lower()
|
|
@@ -301,22 +341,23 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
|
|
|
301
341
|
if not dkim_selector:
|
|
302
342
|
raise SndEmailError (f"snd_email - Config <EmailDKIMSelector> is required for SMTP DKIM signing")
|
|
303
343
|
|
|
304
|
-
if smtp_config.getcfg('DontEmail', fallback=False, types=bool, section='SMTP'):
|
|
305
|
-
if log:
|
|
306
|
-
logging.warning (f"Email NOT sent <{subj}>")
|
|
307
|
-
else:
|
|
308
|
-
logging.debug (f"Email NOT sent <{subj}>")
|
|
309
|
-
return
|
|
310
|
-
|
|
311
|
-
|
|
312
344
|
# Send the message, with retries
|
|
313
345
|
for trynum in range(ntries):
|
|
314
346
|
try:
|
|
315
347
|
msg = MIMEText(m_text, msg_type)
|
|
316
348
|
msg['Subject'] = subj
|
|
317
|
-
msg['From']
|
|
318
|
-
msg['To']
|
|
319
|
-
msg["Date"]
|
|
349
|
+
msg['From'] = email_from
|
|
350
|
+
msg['To'] = ", ".join(To)
|
|
351
|
+
msg["Date"] = formatdate(localtime=True)
|
|
352
|
+
|
|
353
|
+
# logging.debug (msg)
|
|
354
|
+
|
|
355
|
+
if smtp_config.getcfg('DontEmail', fallback=False, types=bool, section='SMTP'):
|
|
356
|
+
if log:
|
|
357
|
+
logging.warning (f"Email NOT sent <{subj}>")
|
|
358
|
+
else:
|
|
359
|
+
logging.debug (f"Email NOT sent <{subj}>")
|
|
360
|
+
return
|
|
320
361
|
|
|
321
362
|
# Add DKIM signature if EmailDKIMDomain is specified
|
|
322
363
|
if dkim_domain:
|
|
@@ -331,11 +372,11 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
|
|
|
331
372
|
|
|
332
373
|
logging.debug (f"Initialize the SMTP server connection for port <{cfg_port}>")
|
|
333
374
|
if cfg_port == "p25":
|
|
334
|
-
server = smtplib.SMTP(cfg_server, 25, timeout=
|
|
375
|
+
server = smtplib.SMTP(cfg_server, 25, timeout=server_timeout)
|
|
335
376
|
elif cfg_port == "p465":
|
|
336
|
-
server = smtplib.SMTP_SSL(cfg_server, 465, timeout=
|
|
377
|
+
server = smtplib.SMTP_SSL(cfg_server, 465, timeout=server_timeout)
|
|
337
378
|
else: # cfg_port == "p587" or "p587tls"
|
|
338
|
-
server = smtplib.SMTP(cfg_server, 587, timeout=
|
|
379
|
+
server = smtplib.SMTP(cfg_server, 587, timeout=server_timeout)
|
|
339
380
|
|
|
340
381
|
if smtp_config.getcfg("EmailVerbose", False, types=[bool], section='SMTP'):
|
|
341
382
|
logging.debug ("Set SMTP connection debuglevel(1)")
|
|
@@ -362,10 +403,100 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
|
|
|
362
403
|
|
|
363
404
|
except Exception as e:
|
|
364
405
|
last_error = e
|
|
365
|
-
if logging.getLogger().level == logging.DEBUG:
|
|
366
|
-
logging.exception(f"Email send try {trynum} failed:")
|
|
367
406
|
if trynum < ntries -1:
|
|
407
|
+
logging.debug(f"Email send try {trynum} failed. Retry in <{retry_wait} sec>:\n <{e}>")
|
|
368
408
|
time.sleep(retry_wait)
|
|
369
409
|
continue
|
|
370
410
|
|
|
371
411
|
raise SndEmailError (f"snd_email: Send failed for <{subj}>:\n <{last_error}>")
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
#=====================================================================================
|
|
415
|
+
#=====================================================================================
|
|
416
|
+
# l i s t _ t o
|
|
417
|
+
#=====================================================================================
|
|
418
|
+
#=====================================================================================
|
|
419
|
+
|
|
420
|
+
def list_to(raw_in, get_type, subj, smtp_config):
|
|
421
|
+
"""
|
|
422
|
+
### list_to(raw_in, get_type, subj, smtp_config) - Build list of phone numbers or email addresses from raw_in
|
|
423
|
+
|
|
424
|
+
`list_to` handles several translations, controlled by `get_type` ('numbers' or 'emails'), including dereferencing through
|
|
425
|
+
config param, extracting and constructing a proper phone number list for messaging services (eg, Twilio), and constructing an
|
|
426
|
+
email address list.
|
|
427
|
+
|
|
428
|
+
### Parameters
|
|
429
|
+
`raw_in` (str or int (in the case of a single phone number))
|
|
430
|
+
- A string list of phone numbers or email addresses, separated by either whitespace or ','
|
|
431
|
+
- If the value is the name of a param in the smtp_config [SMTP] section then that param's value is used, else `raw_in` is directly parsed
|
|
432
|
+
- Phone numbers may optionally include '+<country_code>', eg +14325551212
|
|
433
|
+
|
|
434
|
+
`get_type` (str)
|
|
435
|
+
- 'numbers' - a list of 1 or more phone numbers will be returned
|
|
436
|
+
- '+<country_code>', eg '+1' is prepended to each number, if not provided
|
|
437
|
+
- If the `raw_in` is one or more email-to-SMS gateway addresses (eg, 4805551212@vzwpix.com), then the local-part (the part before '@') is extracted as a phone number.
|
|
438
|
+
This feature enables a config parameter containing a list of carrier email-to-SMS gateway addresses to be directly used with a SMS/MMS messaging service such as Twilio.
|
|
439
|
+
- 'emails' - a list of 1 or more email addresses will be returned
|
|
440
|
+
- Address validity checking is minimal: Email addresses must contain an '@'.
|
|
441
|
+
|
|
442
|
+
`subj` (str)
|
|
443
|
+
- The notification or email subject field - used only for raised errors to aid debug tracing
|
|
444
|
+
|
|
445
|
+
`smtp_config` (config_item class instance)
|
|
446
|
+
- config_item class instance containing the [SMTP] section and related params
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
### config dictionary params in the [SMTP] section
|
|
450
|
+
`country_code` (int or str, default 1 (US/Canada), required only if `get_type='numbers'`)
|
|
451
|
+
- Number without a preceding '+', eg '1' for US/Canada phone numbers
|
|
452
|
+
- If `get_type='numbers'` then each phone number is prepended with `+` plus `country_code` (eg, '+1'), but only if the number does not already have a country code.
|
|
453
|
+
- If a `raw_in` phone number has a different country code, it is retained.
|
|
454
|
+
|
|
455
|
+
`number_length` (int, default 10 (US/Canada), required only if `get_type= 'numbers'`)
|
|
456
|
+
- The number of digits in a valid phone number (not including the country code) for the given `country_code`, eg 10 for US/Canada phone numbers
|
|
457
|
+
|
|
458
|
+
### Returns
|
|
459
|
+
- Either a list of phone numbers or a list of email addresses, eg:
|
|
460
|
+
- ['+14325551212']
|
|
461
|
+
- ['+14325551212', '+14802345678']
|
|
462
|
+
- ['4325551212@txt.att.net', '4802345678@vxwpix.com', 'myemail@tmomail.net']
|
|
463
|
+
- Raises SndEmailError on any errors
|
|
464
|
+
"""
|
|
465
|
+
|
|
466
|
+
xx = smtp_config.getcfg(raw_in, fallback=None, section='SMTP')
|
|
467
|
+
if xx: # raw_in is a config-defined param (of 1 or more phone numbers)
|
|
468
|
+
raw_in = xx
|
|
469
|
+
|
|
470
|
+
items = re.split(r'[,\s]+', str(raw_in))
|
|
471
|
+
cc = None # Force load once per call
|
|
472
|
+
to_list = []
|
|
473
|
+
|
|
474
|
+
for item in items:
|
|
475
|
+
if get_type == 'numbers':
|
|
476
|
+
if not cc:
|
|
477
|
+
cc = '+' + str(smtp_config.getcfg('country_code', COUNTRY_CODE, section='SMTP')) # '+1'
|
|
478
|
+
num_len = smtp_config.getcfg('number_length', PHONE_NUM_LENGTH, section='SMTP') # 10
|
|
479
|
+
if '@' in item:
|
|
480
|
+
num_part = item.split('@')[0]
|
|
481
|
+
else:
|
|
482
|
+
num_part = item
|
|
483
|
+
|
|
484
|
+
if num_part.startswith(cc): # Strip optional default country code prefix
|
|
485
|
+
num_part = num_part.replace(cc,'')
|
|
486
|
+
|
|
487
|
+
if num_part.startswith('+') and num_part[1:].isdigit(): # Non-default country code
|
|
488
|
+
to_list.append(num_part)
|
|
489
|
+
elif num_part.isdigit() and len(num_part) == num_len: # No country code prefix remaining
|
|
490
|
+
to_list.append(cc + num_part)
|
|
491
|
+
else:
|
|
492
|
+
raise SndEmailError (f"Message subject <{subj}>: <{num_part}> is not a valid phone number")
|
|
493
|
+
|
|
494
|
+
elif get_type == 'emails':
|
|
495
|
+
if '@' not in item:
|
|
496
|
+
raise SndEmailError (f"Message subject <{subj}>: <{item}> is not a valid email address")
|
|
497
|
+
to_list.append(item)
|
|
498
|
+
|
|
499
|
+
else:
|
|
500
|
+
raise SndEmailError (f"Message subject <{subj}>: <{get_type}> is not a valid get_type for list_to()")
|
|
501
|
+
|
|
502
|
+
return (to_list)
|