cjnfuncs 2.1__tar.gz → 2.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cjnfuncs
3
- Version: 2.1
3
+ Version: 2.2
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
@@ -31,6 +31,7 @@ Description-Content-Type: text/markdown
31
31
  License-File: LICENSE.txt
32
32
  Requires-Dist: requests
33
33
  Requires-Dist: appdirs>=1.4
34
+ Requires-Dist: dkimpy
34
35
  Requires-Dist: importlib_resources
35
36
  Requires-Dist: posix-ipc>=1.1.1
36
37
 
@@ -45,13 +46,13 @@ module | Description/Purpose
45
46
  [core](core.md) | Set up the base environment
46
47
  [configman](configman.md) | Feature-rich configuration file toolset
47
48
  [timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes)
48
- [mungePath](mungePath.md) | Ease-of-use pathlib extenstion for constructing and manipulating file paths
49
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
49
50
  [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
50
51
  [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
51
52
  [SMTP](SMTP.md) | Send notification and email messages
52
53
 
53
54
  Developed and tested on Python 3.6.8, and supported on all higher Python versions.
54
- Developed on Linux, supported also on Windows (tested on Windows 10).
55
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
55
56
 
56
57
  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.
57
58
 
@@ -74,6 +75,7 @@ Project repo: https://github.com/cjnaz/cjnfuncs
74
75
  <br/>
75
76
 
76
77
  ## Revision history
78
+ - 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
77
79
  - 2.1 240104 - Partitioned to separate modules.
78
80
  Added modify_configfile.
79
81
  Added native support for float, list, tuple, and dict in loadconfig().
@@ -9,13 +9,13 @@ module | Description/Purpose
9
9
  [core](core.md) | Set up the base environment
10
10
  [configman](configman.md) | Feature-rich configuration file toolset
11
11
  [timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes)
12
- [mungePath](mungePath.md) | Ease-of-use pathlib extenstion for constructing and manipulating file paths
12
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
13
13
  [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
14
14
  [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
15
15
  [SMTP](SMTP.md) | Send notification and email messages
16
16
 
17
17
  Developed and tested on Python 3.6.8, and supported on all higher Python versions.
18
- Developed on Linux, supported also on Windows (tested on Windows 10).
18
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
19
19
 
20
20
  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.
21
21
 
@@ -38,6 +38,7 @@ Project repo: https://github.com/cjnaz/cjnfuncs
38
38
  <br/>
39
39
 
40
40
  ## Revision history
41
+ - 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
41
42
  - 2.1 240104 - Partitioned to separate modules.
42
43
  Added modify_configfile.
43
44
  Added native support for float, list, tuple, and dict in loadconfig().
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "cjnfuncs"
8
- version = "2.1"
8
+ version = "2.2"
9
9
  description = "A collection of core functions for tool script writing"
10
10
  readme = "README.md"
11
11
  requires-python = ">=3.6" # Centos 7 uses 3.6.8
@@ -14,6 +14,7 @@ license = {file = "LICENSE.txt"}
14
14
  dependencies = [
15
15
  'requests',
16
16
  'appdirs >= 1.4',
17
+ 'dkimpy',
17
18
  'importlib_resources', #; python_version < "3.9"', # in 2.0.1, used for all python versions
18
19
  'posix-ipc >= 1.1.1'
19
20
  ]
@@ -11,7 +11,9 @@
11
11
  import time
12
12
  import smtplib
13
13
  from email.mime.text import MIMEText
14
+ from email.utils import formatdate
14
15
  from pathlib import Path
16
+ import dkim
15
17
 
16
18
  from .core import logging, SndEmailError
17
19
  from .mungePath import mungePath
@@ -20,7 +22,7 @@ import cjnfuncs.core as core
20
22
 
21
23
  # Configs / Constants
22
24
  SND_EMAIL_NTRIES = 3 # Number of tries to send email before aborting
23
- SND_EMAIL_WAIT = '5s' # seconds between retries
25
+ SND_EMAIL_WAIT = '2s' # seconds between retries, and server connection timeout
24
26
 
25
27
 
26
28
  #=====================================================================================
@@ -68,7 +70,7 @@ The `subj` field is part of the log message.
68
70
  - config_item class instance containing the [SMTP] section and related params
69
71
 
70
72
 
71
- ### cfg dictionary params in the [SMTP] section
73
+ ### cfg dictionary params in the [SMTP] section, in addition to the cfg dictionary params required for snd_email
72
74
  `NotifList` (optional)
73
75
  - string list of email addresses (whitespace or comma separated).
74
76
  - Defining `NotifList` in the config is only required if any call to `snd_notif()` uses this
@@ -79,6 +81,8 @@ default `to` parameter value.
79
81
  messages are also blocked if `DontEmail` is True.
80
82
 
81
83
 
84
+
85
+
82
86
  ### Returns
83
87
  - NoneType
84
88
  - Raises `SndEmailError` on error
@@ -121,7 +125,9 @@ or a string with one or more email addresses. Using a config param name allows f
121
125
  `to` addresses without having to edit the code.
122
126
 
123
127
  What to send may be a `body` string, the text contents of `filename`, or the HTML-formatted contents
124
- of `htmlfile`, in this order of precedent.
128
+ of `htmlfile`, in this order of precedent. MIME multi-part is not supported.
129
+
130
+ DKIM signing is optionally supported.
125
131
 
126
132
  Three attempts are made to send the message (see `EmailNTries`, below).
127
133
 
@@ -179,8 +185,21 @@ The `subj` field is part of the log message.
179
185
  `EmailNTries` (type int, default 3)
180
186
  - Number of tries to send email before aborting
181
187
 
182
- `EmailRetryWait` (seconds, type int, float, or timevalue, default 5s)
188
+ `EmailRetryWait` (seconds, type int, float, or timevalue, default 2s)
183
189
  - Number of seconds to wait between retry attempts
190
+ - Also used for server connection timeout
191
+
192
+ `EmailDKIMDomain` (required if using DKIM email signing)
193
+ - The domain of the public-facing SMTP server, eg `mydomain.com`
194
+ - Defining `EmailDKIMDomain` enables DKIM signing, and also requires `EmailDKIMPem` and `EmailDKIMSelector`
195
+
196
+ `EmailDKIMPem` (required if using DKIM email signing)
197
+ - Full path to the private key file of the public-facing SMTP server at the `EmailDomain`, eg `/home/me/creds_mydomain.com.pem`
198
+ - Make sure this file is readable only to the user
199
+ - You may be able to obtain this key in cPanel for your shared-hosting service
200
+
201
+ `EmailDKIMSelector` (required if using DKIM email signing)
202
+ - The DKIM selector string, eg 'default'
184
203
 
185
204
 
186
205
  ### Returns
@@ -202,6 +221,7 @@ Some email servers require that the `EmailFrom` address be of the same domain as
202
221
  so it may be practical to bundle `EmailFrom` with the server specifics. Place all of these in
203
222
  `~/creds_SMTP`:
204
223
  - `EmailFrom`, `EmailServer`, `EmailServerPort`, `EmailUser`, and `EmailPass`
224
+ - If DKIM signing is used, also include `EmailDKIMDomain`, `EmailDKIMPem`, and `EmailDKIMSelector`
205
225
  - `snd_email()` does not support multi-part MIME (an html send wont have a plain text part).
206
226
  - Checking the validity of email addresses is very basic... an email address must contain an '@'.
207
227
  """
@@ -260,16 +280,26 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
260
280
  raise SndEmailError (f"snd_email - Message subject <{subj}>: address in 'to' list is invalid: <{address}>.")
261
281
 
262
282
  # Gather, check remaining config params
263
- ntries = smtp_config.getcfg('EmailNTries', SND_EMAIL_NTRIES, types=int, section='SMTP')
264
- retry_wait = timevalue(smtp_config.getcfg('EmailRetryWait', SND_EMAIL_WAIT, types=[int, float, str], section='SMTP')).seconds
265
- email_from = smtp_config.getcfg('EmailFrom', types=str, section='SMTP')
266
- cfg_server = smtp_config.getcfg('EmailServer', types=str, section='SMTP')
267
- cfg_port = smtp_config.getcfg('EmailServerPort', types=str, section='SMTP').lower()
283
+ ntries = smtp_config.getcfg('EmailNTries', SND_EMAIL_NTRIES, types=int, section='SMTP')
284
+ retry_wait = timevalue(smtp_config.getcfg('EmailRetryWait', SND_EMAIL_WAIT, types=[int, float, str], section='SMTP')).seconds
285
+ email_from = smtp_config.getcfg('EmailFrom', types=str, section='SMTP')
286
+ cfg_server = smtp_config.getcfg('EmailServer', types=str, section='SMTP')
287
+ cfg_port = smtp_config.getcfg('EmailServerPort', types=str, section='SMTP').lower()
268
288
  if cfg_port not in ['p25', 'p465', 'p587', 'p587tls']:
269
- raise SndEmailError (f"snd_email - Config EmailServerPort <{smtp_config.getcfg('EmailServerPort', fallback='', section='SMTP')}> is invalid")
270
- email_user = str(smtp_config.getcfg('EmailUser', None, types=[str, int, float], section='SMTP')) # username may be numeric
289
+ raise SndEmailError (f"snd_email - Config EmailServerPort <{cfg_port}> is invalid")
290
+
291
+ email_user = str(smtp_config.getcfg('EmailUser', None, types=[str, int, float], section='SMTP')) # username may be numeric - optional
271
292
  if email_user:
272
- email_pass = str(smtp_config.getcfg('EmailPass', types=[str, int, float], section='SMTP')) # password may be numeric
293
+ email_pass = str(smtp_config.getcfg('EmailPass', types=[str, int, float], section='SMTP')) # password may be numeric - required if EmailUser provided
294
+
295
+ dkim_domain = smtp_config.getcfg('EmailDKIMDomain', None, types=str, section='SMTP')
296
+ if dkim_domain:
297
+ dkim_pem = smtp_config.getcfg('EmailDKIMPem', None, types=str, section='SMTP')
298
+ if not dkim_pem:
299
+ raise SndEmailError (f"snd_email - Config <EmailDKIMPem> is required for SMTP DKIM signing")
300
+ dkim_selector = smtp_config.getcfg('EmailDKIMSelector', None, types=str, section='SMTP')
301
+ if not dkim_selector:
302
+ raise SndEmailError (f"snd_email - Config <EmailDKIMSelector> is required for SMTP DKIM signing")
273
303
 
274
304
  if smtp_config.getcfg('DontEmail', fallback=False, types=bool, section='SMTP'):
275
305
  if log:
@@ -278,6 +308,7 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
278
308
  logging.debug (f"Email NOT sent <{subj}>")
279
309
  return
280
310
 
311
+
281
312
  # Send the message, with retries
282
313
  for trynum in range(ntries):
283
314
  try:
@@ -285,21 +316,41 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
285
316
  msg['Subject'] = subj
286
317
  msg['From'] = email_from
287
318
  msg['To'] = ", ".join(To)
288
-
319
+ msg["Date"] = formatdate(localtime=True)
320
+
321
+ # Add DKIM signature if EmailDKIMDomain is specified
322
+ if dkim_domain:
323
+ privateKey = Path(dkim_pem).read_text()
324
+ sig = dkim.sign(message=msg.as_bytes(),
325
+ selector= bytes(dkim_selector, 'UTF8'),
326
+ domain= bytes(dkim_domain, 'UTF8'),
327
+ privkey= bytes(privateKey, 'UTF8'),
328
+ include_headers= ['from', 'to', 'subject', 'date'])
329
+ sig = sig.decode()
330
+ msg['DKIM-Signature'] = sig[len("DKIM-Signature: "):]
331
+
332
+ logging.debug (f"Initialize the SMTP server connection for port <{cfg_port}>")
289
333
  if cfg_port == "p25":
290
- server = smtplib.SMTP(cfg_server, 25)
334
+ server = smtplib.SMTP(cfg_server, 25, timeout=retry_wait)
291
335
  elif cfg_port == "p465":
292
- server = smtplib.SMTP_SSL(cfg_server, 465)
293
- elif cfg_port == "p587":
294
- server = smtplib.SMTP(cfg_server, 587)
295
- else: # cfg_port == "P587TLS":
296
- server = smtplib.SMTP(cfg_server, 587)
297
- server.starttls()
336
+ server = smtplib.SMTP_SSL(cfg_server, 465, timeout=retry_wait)
337
+ else: # cfg_port == "p587" or "p587tls"
338
+ server = smtplib.SMTP(cfg_server, 587, timeout=retry_wait)
298
339
 
299
- if email_user:
300
- server.login (email_user, email_pass)
301
340
  if smtp_config.getcfg("EmailVerbose", False, types=[bool], section='SMTP'):
341
+ logging.debug ("Set SMTP connection debuglevel(1)")
302
342
  server.set_debuglevel(1)
343
+
344
+ if cfg_port == "p587tls":
345
+ logging.debug ("Start TLS")
346
+ server.starttls()
347
+
348
+ # if email_user:
349
+ if cfg_port.startswith('p587'):
350
+ logging.debug (f"Logging into SMTP server")
351
+ server.login (email_user, email_pass)
352
+
353
+ logging.debug (f"Sending message <{subj}>")
303
354
  server.sendmail(email_from, To, msg.as_string())
304
355
  server.quit()
305
356
 
@@ -311,7 +362,8 @@ so it may be practical to bundle `EmailFrom` with the server specifics. Place a
311
362
 
312
363
  except Exception as e:
313
364
  last_error = e
314
- logging.debug(f"Email send try {trynum} failed:\n <{e}>")
365
+ if logging.getLogger().level == logging.DEBUG:
366
+ logging.exception(f"Email send try {trynum} failed:")
315
367
  if trynum < ntries -1:
316
368
  time.sleep(retry_wait)
317
369
  continue
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cjnfuncs
3
- Version: 2.1
3
+ Version: 2.2
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
@@ -31,6 +31,7 @@ Description-Content-Type: text/markdown
31
31
  License-File: LICENSE.txt
32
32
  Requires-Dist: requests
33
33
  Requires-Dist: appdirs>=1.4
34
+ Requires-Dist: dkimpy
34
35
  Requires-Dist: importlib_resources
35
36
  Requires-Dist: posix-ipc>=1.1.1
36
37
 
@@ -45,13 +46,13 @@ module | Description/Purpose
45
46
  [core](core.md) | Set up the base environment
46
47
  [configman](configman.md) | Feature-rich configuration file toolset
47
48
  [timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes)
48
- [mungePath](mungePath.md) | Ease-of-use pathlib extenstion for constructing and manipulating file paths
49
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
49
50
  [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
50
51
  [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
51
52
  [SMTP](SMTP.md) | Send notification and email messages
52
53
 
53
54
  Developed and tested on Python 3.6.8, and supported on all higher Python versions.
54
- Developed on Linux, supported also on Windows (tested on Windows 10).
55
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
55
56
 
56
57
  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.
57
58
 
@@ -74,6 +75,7 @@ Project repo: https://github.com/cjnaz/cjnfuncs
74
75
  <br/>
75
76
 
76
77
  ## Revision history
78
+ - 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
77
79
  - 2.1 240104 - Partitioned to separate modules.
78
80
  Added modify_configfile.
79
81
  Added native support for float, list, tuple, and dict in loadconfig().
@@ -1,4 +1,5 @@
1
1
  requests
2
2
  appdirs>=1.4
3
+ dkimpy
3
4
  importlib_resources
4
5
  posix-ipc>=1.1.1
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes