cjnfuncs 2.5__tar.gz → 3.0__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.5/LICENSE.txt → cjnfuncs-3.0/LICENSE +1 -1
- cjnfuncs-3.0/MANIFEST.in +2 -0
- cjnfuncs-3.0/PKG-INFO +108 -0
- cjnfuncs-3.0/README.md +90 -0
- cjnfuncs-3.0/SMTP.md +402 -0
- cjnfuncs-3.0/configman.md +979 -0
- cjnfuncs-3.0/core.md +544 -0
- cjnfuncs-3.0/deployfiles.md +183 -0
- cjnfuncs-3.0/mungePath.md +283 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/pyproject.toml +11 -4
- cjnfuncs-3.0/resourcelock.md +464 -0
- cjnfuncs-3.0/rwt.md +256 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs/SMTP.py +10 -9
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs/configman.py +82 -83
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs/core.py +194 -18
- cjnfuncs-3.0/src/cjnfuncs/deployfiles.py +213 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs/mungePath.py +97 -43
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs/resourcelock.py +6 -7
- cjnfuncs-3.0/src/cjnfuncs/rwt.py +195 -0
- cjnfuncs-3.0/src/cjnfuncs/timevalue.py +253 -0
- cjnfuncs-3.0/src/cjnfuncs.egg-info/PKG-INFO +108 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs.egg-info/SOURCES.txt +11 -1
- cjnfuncs-3.0/timevalue.md +283 -0
- cjnfuncs-2.5/PKG-INFO +0 -97
- cjnfuncs-2.5/README.md +0 -60
- cjnfuncs-2.5/src/cjnfuncs/deployfiles.py +0 -156
- cjnfuncs-2.5/src/cjnfuncs/timevalue.py +0 -125
- cjnfuncs-2.5/src/cjnfuncs.egg-info/PKG-INFO +0 -97
- {cjnfuncs-2.5 → cjnfuncs-3.0}/setup.cfg +0 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs/__init__.py +0 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs.egg-info/dependency_links.txt +0 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs.egg-info/entry_points.txt +0 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs.egg-info/requires.txt +0 -0
- {cjnfuncs-2.5 → cjnfuncs-3.0}/src/cjnfuncs.egg-info/top_level.txt +0 -0
cjnfuncs-3.0/MANIFEST.in
ADDED
cjnfuncs-3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cjnfuncs
|
|
3
|
+
Version: 3.0
|
|
4
|
+
Summary: A collection of core functions for tool script writing
|
|
5
|
+
Author-email: Chris Nelson <github@cjnaz.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: repository, https://github.com/cjnaz/cjnfuncs
|
|
8
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: requests
|
|
13
|
+
Requires-Dist: appdirs>=1.4
|
|
14
|
+
Requires-Dist: dkimpy
|
|
15
|
+
Requires-Dist: importlib_resources
|
|
16
|
+
Requires-Dist: posix-ipc>=1.1.1
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# cjnfuncs - A framework and collection of utility functions for script writing
|
|
20
|
+
|
|
21
|
+
## cjnfuncs is comprised of several modules (follow links to respective documentation)
|
|
22
|
+
|
|
23
|
+
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.
|
|
24
|
+
|
|
25
|
+
module | Description/Purpose
|
|
26
|
+
--|--
|
|
27
|
+
[core](core.md) | Set up the base environment
|
|
28
|
+
[configman](configman.md) | Feature-rich configuration file toolset
|
|
29
|
+
[timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes), and schedule future operations
|
|
30
|
+
[mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
|
|
31
|
+
[rwt / run_with_timeout](rwt.md) | Execute any function with an enforced timeout
|
|
32
|
+
[deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
|
|
33
|
+
[resourcelock](resourcelock.md) | Inter-process resource lock mechanism
|
|
34
|
+
[SMTP](SMTP.md) | Send notification and email messages
|
|
35
|
+
|
|
36
|
+
Developed and tested on Python 3.9.21 and supported on all higher Python versions.
|
|
37
|
+
Developed on Linux. Not supported on Windows (posix-ipc module dependency).
|
|
38
|
+
|
|
39
|
+
In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
|
|
40
|
+
|
|
41
|
+
<br/>
|
|
42
|
+
|
|
43
|
+
## Installation and usage
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
pip install cjnfuncs
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
A package template using cjnfuncs is available at https://github.com/cjnaz/tool_template, which
|
|
50
|
+
is the basis of PyPI posted tools such as:
|
|
51
|
+
- [lanmonitor](https://pypi.org/project/lanmonitor/)
|
|
52
|
+
- [wanstatus](https://pypi.org/project/wanstatus/)
|
|
53
|
+
- [routermonitor](https://pypi.org/project/routermonitor/)
|
|
54
|
+
|
|
55
|
+
Project repo: https://github.com/cjnaz/cjnfuncs
|
|
56
|
+
|
|
57
|
+
<br/>
|
|
58
|
+
|
|
59
|
+
## Key changes since the prior major public release (version 2.5)
|
|
60
|
+
|
|
61
|
+
`run_with_timeout()` (see module `rwt`)
|
|
62
|
+
- If a network share (or an internet resource) is
|
|
63
|
+
unavailable or extremely slow then the tool script can hang indefinitely. `run_with_timeout()` can wrap any function call
|
|
64
|
+
(any callable - built-in, standard library, installed package, or defined within the tool script) with an enforced timeout
|
|
65
|
+
and number of retries on timeout so that your code can make rational decisions when there are access issues.
|
|
66
|
+
|
|
67
|
+
`set / restore_logging_level()` on a stack (see module `core`)
|
|
68
|
+
- When you want this, you want this. Its used in configman, for instance, to allow for debug logging within the configman code (valuable for cjnfuncs debug and regression testing). If you are developing a hardware sensor driver for example, you can enable debug logging of calls to your driver code
|
|
69
|
+
and restore the level before return.
|
|
70
|
+
You can use `set_logging_level()` standalone, or with later `restore_logging_level()` calls.
|
|
71
|
+
|
|
72
|
+
`periodic_log()` (see module `core`)
|
|
73
|
+
- `periodic_log()` solves the difficulty of finding the sweet spot of how much logging to do to avoiding flooding the log. You can say "log this event only once every 10 minutes", for example. So even if the log event gets triggered every 100 ms, no problem.
|
|
74
|
+
|
|
75
|
+
`get_next_dt()` (see module `timevalue`)
|
|
76
|
+
- A lot of what I develop are process monitoring tools. These typically implement a `while True` loop where various operations get triggered periodically on their own schedules. `get_next_dt()` provides a simple and clean way to get the next `datetime` to do an operation (in my usage, as defined in a config file). `get_next_dt()` supports arbitrary times of day and days of week. For example, trigger generating a summary report every Thursday at 9AM:
|
|
77
|
+
|
|
78
|
+
if now_dt > generate_summary_dt: # I suffix datetimes with '_dt' for readability
|
|
79
|
+
gen_summary()
|
|
80
|
+
generate_summary_dt = get_next_dt('9:00, 'Thursday')
|
|
81
|
+
|
|
82
|
+
`mungePath(..., set_attributes=False)` switch
|
|
83
|
+
- On network outages, my apps would slow to a crawl. The root of the issue was in checking if a network file exists, with no timeout mechanism. The pathlib `.exists()`, `.is_dir()`, and `is_file()` methods are all susceptible to indefinate hangs. The set_attributues switch has been added to mungePath, with a default value of False. _Note that this is a change to default behavior._ If set True then `refresh_stats()` is called (or you can call it directly yourself, as needed). `refresh_stats()` and `check_file_exists()` have been rewritten to utilize `run_with_timeout()`, with a default timeout of 1.0 seconds. I then `periodic_log()` the access problem. Ah, so much more stable.
|
|
84
|
+
|
|
85
|
+
<br/>
|
|
86
|
+
|
|
87
|
+
## Revision history
|
|
88
|
+
- 3.0 250705 - Added run_with_timeout, set / restore_logging_level, periodic_logging, get_next_dt. Functional change to mungePath.
|
|
89
|
+
- 2.5 250206 - Added multi-line and quoted string support to configman
|
|
90
|
+
- 2.4.1 241118 - resource_lock only init lock_info if not existing
|
|
91
|
+
- 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
|
|
92
|
+
- 2.3 240821 - Added mungePath ./ support.
|
|
93
|
+
Resolved check_path_exists() memory leak.
|
|
94
|
+
Added `same_process_ok` to resourcelock.getlock()
|
|
95
|
+
Added prereload_callback to config_item.loadconfig()
|
|
96
|
+
- 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
|
|
97
|
+
- 2.1 240104 - Partitioned to separate modules.
|
|
98
|
+
Added modify_configfile.
|
|
99
|
+
Added native support for float, list, tuple, and dict in loadconfig().
|
|
100
|
+
Added getcfg() type checking.
|
|
101
|
+
Documentation touch for logging formats in config file.
|
|
102
|
+
Improved snd_notif failure logging.
|
|
103
|
+
Added email/notif send retries.
|
|
104
|
+
Added resourcelock module.
|
|
105
|
+
- 2.0.1 230222 - deploy_files() fix for files from package
|
|
106
|
+
- 2.0 230208 - Refactored and converted to installed package. Renamed funcs3 to cjnfuncs.
|
|
107
|
+
- ...
|
|
108
|
+
- 0.1 180524 - New. First github posting
|
cjnfuncs-3.0/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# cjnfuncs - A framework and collection of utility functions for script writing
|
|
2
|
+
|
|
3
|
+
## cjnfuncs is comprised of several modules (follow links to respective documentation)
|
|
4
|
+
|
|
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
|
+
|
|
7
|
+
module | Description/Purpose
|
|
8
|
+
--|--
|
|
9
|
+
[core](core.md) | Set up the base environment
|
|
10
|
+
[configman](configman.md) | Feature-rich configuration file toolset
|
|
11
|
+
[timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes), and schedule future operations
|
|
12
|
+
[mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
|
|
13
|
+
[rwt / run_with_timeout](rwt.md) | Execute any function with an enforced timeout
|
|
14
|
+
[deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
|
|
15
|
+
[resourcelock](resourcelock.md) | Inter-process resource lock mechanism
|
|
16
|
+
[SMTP](SMTP.md) | Send notification and email messages
|
|
17
|
+
|
|
18
|
+
Developed and tested on Python 3.9.21 and supported on all higher Python versions.
|
|
19
|
+
Developed on Linux. Not supported on Windows (posix-ipc module dependency).
|
|
20
|
+
|
|
21
|
+
In this documentation, "tool script" refers to a Python project that imports and uses cjnfuncs. Some may be simple scripts, and others may themselves be installed packages.
|
|
22
|
+
|
|
23
|
+
<br/>
|
|
24
|
+
|
|
25
|
+
## Installation and usage
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
pip install cjnfuncs
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
A package template using cjnfuncs is available at https://github.com/cjnaz/tool_template, which
|
|
32
|
+
is the basis of PyPI posted tools such as:
|
|
33
|
+
- [lanmonitor](https://pypi.org/project/lanmonitor/)
|
|
34
|
+
- [wanstatus](https://pypi.org/project/wanstatus/)
|
|
35
|
+
- [routermonitor](https://pypi.org/project/routermonitor/)
|
|
36
|
+
|
|
37
|
+
Project repo: https://github.com/cjnaz/cjnfuncs
|
|
38
|
+
|
|
39
|
+
<br/>
|
|
40
|
+
|
|
41
|
+
## Key changes since the prior major public release (version 2.5)
|
|
42
|
+
|
|
43
|
+
`run_with_timeout()` (see module `rwt`)
|
|
44
|
+
- If a network share (or an internet resource) is
|
|
45
|
+
unavailable or extremely slow then the tool script can hang indefinitely. `run_with_timeout()` can wrap any function call
|
|
46
|
+
(any callable - built-in, standard library, installed package, or defined within the tool script) with an enforced timeout
|
|
47
|
+
and number of retries on timeout so that your code can make rational decisions when there are access issues.
|
|
48
|
+
|
|
49
|
+
`set / restore_logging_level()` on a stack (see module `core`)
|
|
50
|
+
- When you want this, you want this. Its used in configman, for instance, to allow for debug logging within the configman code (valuable for cjnfuncs debug and regression testing). If you are developing a hardware sensor driver for example, you can enable debug logging of calls to your driver code
|
|
51
|
+
and restore the level before return.
|
|
52
|
+
You can use `set_logging_level()` standalone, or with later `restore_logging_level()` calls.
|
|
53
|
+
|
|
54
|
+
`periodic_log()` (see module `core`)
|
|
55
|
+
- `periodic_log()` solves the difficulty of finding the sweet spot of how much logging to do to avoiding flooding the log. You can say "log this event only once every 10 minutes", for example. So even if the log event gets triggered every 100 ms, no problem.
|
|
56
|
+
|
|
57
|
+
`get_next_dt()` (see module `timevalue`)
|
|
58
|
+
- A lot of what I develop are process monitoring tools. These typically implement a `while True` loop where various operations get triggered periodically on their own schedules. `get_next_dt()` provides a simple and clean way to get the next `datetime` to do an operation (in my usage, as defined in a config file). `get_next_dt()` supports arbitrary times of day and days of week. For example, trigger generating a summary report every Thursday at 9AM:
|
|
59
|
+
|
|
60
|
+
if now_dt > generate_summary_dt: # I suffix datetimes with '_dt' for readability
|
|
61
|
+
gen_summary()
|
|
62
|
+
generate_summary_dt = get_next_dt('9:00, 'Thursday')
|
|
63
|
+
|
|
64
|
+
`mungePath(..., set_attributes=False)` switch
|
|
65
|
+
- On network outages, my apps would slow to a crawl. The root of the issue was in checking if a network file exists, with no timeout mechanism. The pathlib `.exists()`, `.is_dir()`, and `is_file()` methods are all susceptible to indefinate hangs. The set_attributues switch has been added to mungePath, with a default value of False. _Note that this is a change to default behavior._ If set True then `refresh_stats()` is called (or you can call it directly yourself, as needed). `refresh_stats()` and `check_file_exists()` have been rewritten to utilize `run_with_timeout()`, with a default timeout of 1.0 seconds. I then `periodic_log()` the access problem. Ah, so much more stable.
|
|
66
|
+
|
|
67
|
+
<br/>
|
|
68
|
+
|
|
69
|
+
## Revision history
|
|
70
|
+
- 3.0 250705 - Added run_with_timeout, set / restore_logging_level, periodic_logging, get_next_dt. Functional change to mungePath.
|
|
71
|
+
- 2.5 250206 - Added multi-line and quoted string support to configman
|
|
72
|
+
- 2.4.1 241118 - resource_lock only init lock_info if not existing
|
|
73
|
+
- 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
|
|
74
|
+
- 2.3 240821 - Added mungePath ./ support.
|
|
75
|
+
Resolved check_path_exists() memory leak.
|
|
76
|
+
Added `same_process_ok` to resourcelock.getlock()
|
|
77
|
+
Added prereload_callback to config_item.loadconfig()
|
|
78
|
+
- 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
|
|
79
|
+
- 2.1 240104 - Partitioned to separate modules.
|
|
80
|
+
Added modify_configfile.
|
|
81
|
+
Added native support for float, list, tuple, and dict in loadconfig().
|
|
82
|
+
Added getcfg() type checking.
|
|
83
|
+
Documentation touch for logging formats in config file.
|
|
84
|
+
Improved snd_notif failure logging.
|
|
85
|
+
Added email/notif send retries.
|
|
86
|
+
Added resourcelock module.
|
|
87
|
+
- 2.0.1 230222 - deploy_files() fix for files from package
|
|
88
|
+
- 2.0 230208 - Refactored and converted to installed package. Renamed funcs3 to cjnfuncs.
|
|
89
|
+
- ...
|
|
90
|
+
- 0.1 180524 - New. First github posting
|
cjnfuncs-3.0/SMTP.md
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
# SMTP - Wrapper functions for sending text notification and email messages
|
|
2
|
+
|
|
3
|
+
Skip to [API documentation](#links)
|
|
4
|
+
|
|
5
|
+
`snd_notif()` and `snd_email()` are convenience functions that rely on configuration file params in the `[SMTP]` section of the designated config file.
|
|
6
|
+
|
|
7
|
+
A notification message is typically a text message sent to a cell phone number via the carrier's Email-to-SMS gateway, such as vzwpix.com, and has the message text specified in-line rather than attached.
|
|
8
|
+
|
|
9
|
+
For sending notifications, SMS/MMS messaging services, such as Twilio, are also supported. See [Using a Messaging Service, such as Twilio](#ms), below.
|
|
10
|
+
|
|
11
|
+
<br>
|
|
12
|
+
|
|
13
|
+
## A fully working example (enter your own credentials and send-to addresses):
|
|
14
|
+
|
|
15
|
+
Given the following config file - `SMTP_ex1.cfg`:
|
|
16
|
+
```
|
|
17
|
+
# SMTP_ex1.cfg
|
|
18
|
+
|
|
19
|
+
LogLevel = 20
|
|
20
|
+
|
|
21
|
+
# Email and Notifications params
|
|
22
|
+
[SMTP]
|
|
23
|
+
NotifList = 5205551212@vzwpix.com, 6132125555@vzwpix.com # Notifications - white space or comma separated list
|
|
24
|
+
NotifTech = 8185551212@vzwpix.com # Notifs for code problems
|
|
25
|
+
EmailSummary = George123@gmail.com # Summary reports - white space or comma separated list
|
|
26
|
+
import creds_SMTP # Provides EmailServer, EmailServerPort, EmailUser, EmailPass, and EmailFrom
|
|
27
|
+
#EmailVerbose True # True turns on smtplib diagnostic logging
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
And this `creds_SMTP`:
|
|
31
|
+
```
|
|
32
|
+
# creds_SMTP - Email server credentials
|
|
33
|
+
EmailServer mail.myserver.com
|
|
34
|
+
EmailServerPort P587TLS
|
|
35
|
+
EmailUser outbound@myserver.com
|
|
36
|
+
EmailPass mypassword
|
|
37
|
+
EmailFrom me@myserver.com
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
And running this code:
|
|
41
|
+
```
|
|
42
|
+
#!/usr/bin/env python3
|
|
43
|
+
# ***** SMTP_ex1.py *****
|
|
44
|
+
|
|
45
|
+
from cjnfuncs.core import set_toolname, logging, SndEmailError
|
|
46
|
+
from cjnfuncs.configman import config_item
|
|
47
|
+
from cjnfuncs.deployfiles import deploy_files
|
|
48
|
+
from cjnfuncs.SMTP import snd_notif, snd_email
|
|
49
|
+
|
|
50
|
+
tool = set_toolname('SMTP_ex1')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
deploy_files([
|
|
54
|
+
{ 'source': 'SMTP_ex1.cfg', 'target_dir': 'USER_CONFIG_DIR' },
|
|
55
|
+
{ 'source': 'creds_SMTP', 'target_dir': 'USER_CONFIG_DIR' },
|
|
56
|
+
])
|
|
57
|
+
|
|
58
|
+
myconfig = config_item('SMTP_ex1.cfg')
|
|
59
|
+
myconfig.loadconfig()
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
snd_notif(subj='My first text message',
|
|
63
|
+
msg='This is pretty clean interface!',
|
|
64
|
+
to='NotifTech',
|
|
65
|
+
log=True,
|
|
66
|
+
smtp_config=myconfig)
|
|
67
|
+
except SndEmailError as e:
|
|
68
|
+
logging.warning(f"snd_notif() failed:\n {e}")
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
snd_email(subj='My first email send',
|
|
72
|
+
to='me@gmail.com',
|
|
73
|
+
body='This is the body text of the message',
|
|
74
|
+
log=True,
|
|
75
|
+
smtp_config=myconfig)
|
|
76
|
+
except SndEmailError as e:
|
|
77
|
+
logging.warning(f"snd_email() failed:\n {e}")
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
And finally, running the code produces this output, and a couple sent messages:
|
|
81
|
+
```
|
|
82
|
+
$ ./SMTP_ex1.py
|
|
83
|
+
Deployed SMTP_ex1.cfg to /home/me/.config/SMTP_ex1/SMTP_ex1.cfg
|
|
84
|
+
Deployed creds_SMTP to /home/me/.config/SMTP_ex1/creds_SMTP
|
|
85
|
+
SMTP.snd_notif - WARNING: Notification sent <My first text message> <This is pretty clean interface!>
|
|
86
|
+
SMTP.snd_email - WARNING: Email sent <My first email send>
|
|
87
|
+
```
|
|
88
|
+
Notables:
|
|
89
|
+
- The [SMTP] section of the specified config file (eg, `myconfig`) holds all of the static email settings, while the individual calls to snd_notif() and snd_email() contain the message specifics.
|
|
90
|
+
- A SndEmailError is raised for any issues, and should be trapped in the script code.
|
|
91
|
+
|
|
92
|
+
<br>
|
|
93
|
+
|
|
94
|
+
## Sending DKIM signed messages
|
|
95
|
+
|
|
96
|
+
DKIM signed messages can greatly reduce the chance that the recipient's email server (eg, gmail) classifies your messages as spam.
|
|
97
|
+
You will want to configure DKIM if you are sending through a shared-hosting SMTP server. Your shared-hosting SMTP server should
|
|
98
|
+
also have SPF configured (no action required on your part).
|
|
99
|
+
If you are sending through your ISP's SMTP server it may be adding DKIM signing (and SPF) for you (don't configure DKIM here).
|
|
100
|
+
|
|
101
|
+
For shared-hosting SMTP you may be able to obtain the server's private key from the
|
|
102
|
+
cPanel interface for your account (check in Email Deliverability).
|
|
103
|
+
Save this key to a user-read-only file, eg, `/home/me/creds_mydomain.com.pem`.
|
|
104
|
+
Set the `EmailDKIMSelector` as defined on your SMTP server, eg `default` if your server's DKIM Name filed is `default._domainkey.mydomain.com.`.
|
|
105
|
+
|
|
106
|
+
Add these params to the `creds_SMTP` file:
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
EmailDKIMDomain mydomain.com
|
|
110
|
+
EmailDKIMPem /home/me/creds_mydomain.com.pem
|
|
111
|
+
EmailDKIMSelector default
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
<a id="ms"></a>
|
|
116
|
+
|
|
117
|
+
<br>
|
|
118
|
+
|
|
119
|
+
## Using a Messaging Service, such as Twilio
|
|
120
|
+
|
|
121
|
+
snd_notif() supports sending SMS messages either using the phone number carrier's Email-to-SMS gateway (eg, 4805551212@txt.att.net), or
|
|
122
|
+
using an SMS messaging service, such as Twilio. To configure a messaging service, specify the path to a message sender plugin module
|
|
123
|
+
via the `Msg_Handler` config param (within the [SMTP] section). If `Msg_Handler` is defined, then the plugin's sender() function will be called
|
|
124
|
+
instead of sending the message via snd_email().
|
|
125
|
+
|
|
126
|
+
### Example twilioSender.py plugin:
|
|
127
|
+
|
|
128
|
+
```
|
|
129
|
+
__version__ = '1.0'
|
|
130
|
+
|
|
131
|
+
from twilio.rest import Client
|
|
132
|
+
import logging
|
|
133
|
+
|
|
134
|
+
DEFAULT_LOGLEVEL = 30
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def sender (package, config):
|
|
138
|
+
logging.debug (package)
|
|
139
|
+
|
|
140
|
+
account_sid = config.getcfg('account_sid', section='SMTP')
|
|
141
|
+
auth_token = config.getcfg('auth_token', section='SMTP')
|
|
142
|
+
ms_sid = config.getcfg('messaging_service_sid', section='SMTP'),
|
|
143
|
+
|
|
144
|
+
# Twilio REST API generates tons of INFO level logging, thus a separate Twilio_LogLevel control
|
|
145
|
+
preexisting_loglevel = logging.getLogger().level
|
|
146
|
+
logging.getLogger().setLevel(config.getcfg('Twilio_LogLevel', DEFAULT_LOGLEVEL, section='SMTP'))
|
|
147
|
+
|
|
148
|
+
client = Client(account_sid, auth_token)
|
|
149
|
+
for to_number in package['to']:
|
|
150
|
+
message = client.messages.create(
|
|
151
|
+
to = to_number,
|
|
152
|
+
messaging_service_sid = ms_sid,
|
|
153
|
+
media_url = package['urls'],
|
|
154
|
+
body = f"Subject: {package['subj']}\n{package['msg']}")
|
|
155
|
+
|
|
156
|
+
logging.debug (message.body)
|
|
157
|
+
|
|
158
|
+
logging.getLogger().setLevel(preexisting_loglevel)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Example creds_twilio file:
|
|
162
|
+
|
|
163
|
+
Messaging service credentials should be stored in a private, secured file, and imported into script's config SMTP section.
|
|
164
|
+
In this example, all messaging service related params are being declared in the credential file:
|
|
165
|
+
|
|
166
|
+
```
|
|
167
|
+
Msg_Handler = /<abs-path-to>/twilioSender.py
|
|
168
|
+
# country_code = 1 # No leading '+', default 1
|
|
169
|
+
# number_length = 10 # Default 10
|
|
170
|
+
# Twilio_LogLevel = 10 # Log level within twilloSender, default 30
|
|
171
|
+
|
|
172
|
+
account_sid = AC9b0ad6...
|
|
173
|
+
auth_token = 05975652...
|
|
174
|
+
messaging_service_sid = MG3a225f...
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Notables
|
|
178
|
+
|
|
179
|
+
- If using a messaging service, such as Twilio, the config `Msg_Handler` param declares the path to the message sending plugin module. The module must implement a `sender()`
|
|
180
|
+
function, which will be called with a `package` dictionary containing `subj`, `msg`, `urls`, and `to` key:value pairs, and a reference to the `smtp_config` (the user script
|
|
181
|
+
config that contains the [SMTP] section).
|
|
182
|
+
- snd_notif() and snd_email() use the `list_to()` helper function (see `SMTP.py`) for parsing and translating phone numbers and email addresses. `list_to()` supports:
|
|
183
|
+
- Extracting phone numbers from Email-to-SMS gateway email addresses (eg, 48045551212@vzwpix.com)
|
|
184
|
+
- Prepending the country code, if not provided for a number
|
|
185
|
+
- Basic validity checking of the phone number (all digits and proper length for the specified country code)
|
|
186
|
+
- Dereferencing numbers/email addresses thru config params (eg, `NotifList`)
|
|
187
|
+
- Building a list of numbers for the plugin handler to iterate thru
|
|
188
|
+
- Example: Given `'4805551212@vzwpix.com 4805551213 +14805551214, +44123456'`, list_to() returns: `['+14805551212', '+14805551213', '+14805551214', '+44123456']`
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
<a id="links"></a>
|
|
193
|
+
|
|
194
|
+
<br>
|
|
195
|
+
|
|
196
|
+
---
|
|
197
|
+
|
|
198
|
+
# Links to classes, methods, and functions
|
|
199
|
+
|
|
200
|
+
- [snd_notif](#snd_notif)
|
|
201
|
+
- [snd_email](#snd_email)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
<br/>
|
|
206
|
+
|
|
207
|
+
<a id="snd_notif"></a>
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
# 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
|
|
212
|
+
|
|
213
|
+
Intended for use the mobile provider's (carrier's) email-to-SMS gateway email address, eg,
|
|
214
|
+
`5405551212@vzwtxt.com` for Verizon, but any email address will work.
|
|
215
|
+
|
|
216
|
+
The `to` string may be the name of a config param (who's value is one or more email addresses, default
|
|
217
|
+
"NotifList"), or a string with one or more email addresses. Using a config param name allows for customizing the
|
|
218
|
+
`to` addresses without having to edit the code.
|
|
219
|
+
|
|
220
|
+
The message to send is passed in the `msg` arg as a text string.
|
|
221
|
+
Three attempts are made to send the message.
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
### Args
|
|
225
|
+
`subj` (str, default 'Notification message')
|
|
226
|
+
- Text message subject field
|
|
227
|
+
- Some SMS/MMS apps display the subj field in bold, some in raw form, and some not at all.
|
|
228
|
+
|
|
229
|
+
`msg` (str, default '')
|
|
230
|
+
- Text message body
|
|
231
|
+
|
|
232
|
+
`urls_list` (list, default [])
|
|
233
|
+
- A list of url strings to be passed to the message sending plugin module, which should pass them to the messaging service.
|
|
234
|
+
- This list is discarded by `snd_notif()` if not using a messaging service. If you want to send a message with
|
|
235
|
+
urls then included them in the `msg` body text.
|
|
236
|
+
|
|
237
|
+
`to` (str, default 'NotifList')
|
|
238
|
+
- To whom to send the message. `to` may be either an explicit string list of email addresses
|
|
239
|
+
(whitespace or comma separated) or a config param name (also listing one
|
|
240
|
+
or more whitespace or comma separated email addresses). If the `to` arg does not
|
|
241
|
+
contain an '@' it is assumed to be a config param.
|
|
242
|
+
- Define `NotifList` in the config file to use the default `to` value.
|
|
243
|
+
|
|
244
|
+
`log` (bool, default False)
|
|
245
|
+
- If True, logs that the message was sent at the WARNING level. If False, logs
|
|
246
|
+
at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
|
|
247
|
+
The `subj` field is part of the log message.
|
|
248
|
+
|
|
249
|
+
`smtp_config` (config_item class instance)
|
|
250
|
+
- config_item class instance containing the [SMTP] section and related params
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
### config dictionary params in the [SMTP] section, in addition to the config dictionary params required for snd_email
|
|
254
|
+
|
|
255
|
+
`NotifList` (optional)
|
|
256
|
+
- string list of email addresses (whitespace or comma separated).
|
|
257
|
+
- Defining `NotifList` in the config is only required if any call to `snd_notif()` uses this
|
|
258
|
+
default `to` arg value.
|
|
259
|
+
|
|
260
|
+
`DontNotif` (default False)
|
|
261
|
+
- If True, notification messages are not sent. `log` is still honored. Useful for debug.
|
|
262
|
+
- Setting `DontEmail` True also blocks sending notification messages if using a carrier email-to-SMS gateway
|
|
263
|
+
(not using a messaging service). If using a messaging service then `DontEmail` has no effect.
|
|
264
|
+
|
|
265
|
+
`Msg_Handler` (str, absolute path or package.module, default None)
|
|
266
|
+
- If using a messaging service, such as Twilio, this param declares the path to the message sending plugin module.
|
|
267
|
+
- 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
|
|
268
|
+
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.
|
|
269
|
+
- `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`).
|
|
270
|
+
|
|
271
|
+
`country_code` (int or str, default 1 (US/Canada), required only if `Msg_Handler` is defined in the config [SMTP] section)
|
|
272
|
+
- Number without a preceding '+', eg '1' for US/Canada phone numbers
|
|
273
|
+
- 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.
|
|
274
|
+
- If a `to` phone number has a different country code, it is retained.
|
|
275
|
+
|
|
276
|
+
`number_length` (int, default 10 (US/Canada), required only if `Msg_Handler` is defined in the config [SMTP] section)
|
|
277
|
+
- The number of digits in a valid phone number (not including the country code), eg 10 for US/Canada phone numbers
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
### Returns
|
|
281
|
+
- None
|
|
282
|
+
- Raises `SndEmailError` on error
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
### Behaviors and rules
|
|
286
|
+
- `snd_notif()` uses `snd_email()` to send the message. See `snd_email()` for related setup.
|
|
287
|
+
|
|
288
|
+
<br/>
|
|
289
|
+
|
|
290
|
+
<a id="snd_email"></a>
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
# snd_email (subj, to, body=None, filename=None, htmlfile=None, log=False, smtp_config=None) - Send an email message using info from the config file
|
|
295
|
+
|
|
296
|
+
The `to` string may be the name of a config param (who's value is one or more email addresses),
|
|
297
|
+
or a string with one or more email addresses. Using a config param name allows for customizing the
|
|
298
|
+
`to` addresses without having to edit the code.
|
|
299
|
+
|
|
300
|
+
What to send may be a `body` string, the text contents of `filename`, or the HTML-formatted contents
|
|
301
|
+
of `htmlfile`, in this order of precedent. MIME multi-part is not supported.
|
|
302
|
+
|
|
303
|
+
DKIM signing is optionally supported.
|
|
304
|
+
|
|
305
|
+
Three attempts are made to send the message (see `EmailNTries`, below).
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
### Args
|
|
309
|
+
`subj` (str)
|
|
310
|
+
- Email subject text
|
|
311
|
+
|
|
312
|
+
`to` (str)
|
|
313
|
+
- To whom to send the message. `to` may be either an explicit string list of email addresses
|
|
314
|
+
(whitespace or comma separated) or a config param name in the [SMTP] section (also listing one
|
|
315
|
+
or more whitespace or comma separated email addresses). If the `to` arg does not
|
|
316
|
+
contain an '@' it is assumed to be a config param.
|
|
317
|
+
|
|
318
|
+
`body` (str, default None)
|
|
319
|
+
- A string message to be sent
|
|
320
|
+
|
|
321
|
+
`filename` (str, default None)
|
|
322
|
+
- A str or Path to the file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
|
|
323
|
+
|
|
324
|
+
`htmlfile` (str, default None)
|
|
325
|
+
- A str or Path to the html formatted file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
|
|
326
|
+
|
|
327
|
+
`log` (bool, default False)
|
|
328
|
+
- If True, logs that the message was sent at the WARNING level. If False, logs
|
|
329
|
+
at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
|
|
330
|
+
The `subj` field is part of the log message.
|
|
331
|
+
|
|
332
|
+
`smtp_config` (config_item class instance)
|
|
333
|
+
- config_item class instance containing the [SMTP] section and related params
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
### config dictionary params in the [SMTP] section
|
|
337
|
+
`EmailFrom`
|
|
338
|
+
- An email address, such as `me@myserver.com`
|
|
339
|
+
|
|
340
|
+
`EmailServer`
|
|
341
|
+
- The SMTP server name, such as `mail.myserver.com`
|
|
342
|
+
|
|
343
|
+
`EmailServerPort`
|
|
344
|
+
- The SMTP server port (one of `P25`, `P465`, `P587`, or `P587TLS`)
|
|
345
|
+
|
|
346
|
+
`EmailUser`
|
|
347
|
+
- Username for `EmailServer` login, if required by the server
|
|
348
|
+
|
|
349
|
+
`EmailPass`
|
|
350
|
+
- Password for `EmailServer` login, if required by the server
|
|
351
|
+
|
|
352
|
+
`DontEmail` (default False)
|
|
353
|
+
- If True, messages are not sent. Useful for debug. Also blocks `snd_notif()` messages.
|
|
354
|
+
|
|
355
|
+
`EmailVerbose` (default False)
|
|
356
|
+
- If True, detailed transactions with the SMTP server are sent to stdout. Useful for debug.
|
|
357
|
+
|
|
358
|
+
`EmailNTries` (type int, default 3)
|
|
359
|
+
- Number of tries to send email before aborting
|
|
360
|
+
|
|
361
|
+
`EmailRetryWait` (seconds, type int, float, or timevalue, default 2s)
|
|
362
|
+
- Number of seconds to wait between retry attempts
|
|
363
|
+
|
|
364
|
+
`EmailServerTimeout` (seconds, type int, float, or timevalue, default 2s)
|
|
365
|
+
- Server connection timeout
|
|
366
|
+
|
|
367
|
+
`EmailDKIMDomain` (required if using DKIM email signing)
|
|
368
|
+
- The domain of the public-facing SMTP server, eg `mydomain.com`
|
|
369
|
+
- Defining `EmailDKIMDomain` enables DKIM signing, and also requires `EmailDKIMPem` and `EmailDKIMSelector`
|
|
370
|
+
|
|
371
|
+
`EmailDKIMPem` (required if using DKIM email signing)
|
|
372
|
+
- Full path to the private key file of the public-facing SMTP server at the `EmailDomain`, eg `/home/me/creds_mydomain.com.pem`
|
|
373
|
+
- Make sure this file is readable only to the user
|
|
374
|
+
- You may be able to obtain this key in cPanel for your shared-hosting service
|
|
375
|
+
|
|
376
|
+
`EmailDKIMSelector` (required if using DKIM email signing)
|
|
377
|
+
- The DKIM selector string, eg 'default'
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
### Returns
|
|
381
|
+
- None
|
|
382
|
+
- Raises SndEmailError on error
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
### Behaviors and rules
|
|
386
|
+
- One of `body`, `filename`, or `htmlfile` must be specified. Looked for in this order, and the first
|
|
387
|
+
found is used.
|
|
388
|
+
- EmailServerPort must be one of the following:
|
|
389
|
+
- P25: SMTP to port 25 without any encryption
|
|
390
|
+
- P465: SMTP_SSL to port 465
|
|
391
|
+
- P587: SMTP to port 587 without any encryption
|
|
392
|
+
- P587TLS: SMTP to port 587 and with TLS encryption
|
|
393
|
+
- It is recommended (not required) that the email server params be placed in a user-read-only
|
|
394
|
+
file in the user's home directory, such as `~/creds_SMTP`, and imported by the main config file.
|
|
395
|
+
Some email servers require that the `EmailFrom` address be of the same domain as the server,
|
|
396
|
+
so it may be practical to bundle `EmailFrom` with the server specifics. Place all of these in
|
|
397
|
+
`~/creds_SMTP`:
|
|
398
|
+
- `EmailFrom`, `EmailServer`, `EmailServerPort`, `EmailUser`, and `EmailPass`
|
|
399
|
+
- If DKIM signing is used, also include `EmailDKIMDomain`, `EmailDKIMPem`, and `EmailDKIMSelector`
|
|
400
|
+
- `snd_email()` does not support multi-part MIME (an html send wont have a plain text part).
|
|
401
|
+
- Checking the validity of email addresses is very basic... an email address must contain an '@'.
|
|
402
|
+
|