cjnfuncs 2.0.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.
cjnfuncs-2.2/PKG-INFO ADDED
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.1
2
+ Name: cjnfuncs
3
+ Version: 2.2
4
+ Summary: A collection of core functions for tool script writing
5
+ Author-email: Chris Nelson <github@cjnaz.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2019 Chris Nelson
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: repository, https://github.com/cjnaz/cjnfuncs
28
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
+ Requires-Python: >=3.6
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE.txt
32
+ Requires-Dist: requests
33
+ Requires-Dist: appdirs>=1.4
34
+ Requires-Dist: dkimpy
35
+ Requires-Dist: importlib_resources
36
+ Requires-Dist: posix-ipc>=1.1.1
37
+
38
+ # cjnfuncs - A framework and collection of utility functions for script writing
39
+
40
+ ## cjnfuncs is comprised of several modules (links to respective documentation)
41
+
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
+
44
+ module | Description/Purpose
45
+ --|--
46
+ [core](core.md) | Set up the base environment
47
+ [configman](configman.md) | Feature-rich configuration file toolset
48
+ [timevalue](timevalue.md) | Handle time values with units, such as '5m' (5 minutes)
49
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
50
+ [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
51
+ [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
52
+ [SMTP](SMTP.md) | Send notification and email messages
53
+
54
+ Developed and tested on Python 3.6.8, and supported on all higher Python versions.
55
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
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.
58
+
59
+ <br/>
60
+
61
+ ## Installation and usage
62
+
63
+ ```
64
+ pip install cjnfuncs
65
+ ```
66
+
67
+ A package template using cjnfuncs is available at https://github.com/cjnaz/tool_template, which
68
+ is the basis of PyPI posted tools such as:
69
+ - [lanmonitor](https://pypi.org/project/lanmonitor/)
70
+ - [wanstatus](https://pypi.org/project/wanstatus/)
71
+ - [routermonitor](https://pypi.org/project/routermonitor/)
72
+
73
+ Project repo: https://github.com/cjnaz/cjnfuncs
74
+
75
+ <br/>
76
+
77
+ ## Revision history
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-2.2/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # cjnfuncs - A framework and collection of utility functions for script writing
2
+
3
+ ## cjnfuncs is comprised of several modules (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)
12
+ [mungePath](mungePath.md) | Ease-of-use pathlib extension for constructing and manipulating file paths
13
+ [deployfiles](deployfiles.md) | Push bundled setup files within a package to the proper user/system locations
14
+ [resourcelock](resourcelock.md) | Inter-process resource lock mechanism
15
+ [SMTP](SMTP.md) | Send notification and email messages
16
+
17
+ Developed and tested on Python 3.6.8, and supported on all higher Python versions.
18
+ Developed on Linux. Not supported on Windows (posix-ipc module dependency).
19
+
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
+
22
+ <br/>
23
+
24
+ ## Installation and usage
25
+
26
+ ```
27
+ pip install cjnfuncs
28
+ ```
29
+
30
+ A package template using cjnfuncs is available at https://github.com/cjnaz/tool_template, which
31
+ is the basis of PyPI posted tools such as:
32
+ - [lanmonitor](https://pypi.org/project/lanmonitor/)
33
+ - [wanstatus](https://pypi.org/project/wanstatus/)
34
+ - [routermonitor](https://pypi.org/project/routermonitor/)
35
+
36
+ Project repo: https://github.com/cjnaz/cjnfuncs
37
+
38
+ <br/>
39
+
40
+ ## Revision history
41
+ - 2.2 240119 - Added SMTP DKIM support. Set SMTP server connect timeout to EmailRetryWait.
42
+ - 2.1 240104 - Partitioned to separate modules.
43
+ Added modify_configfile.
44
+ Added native support for float, list, tuple, and dict in loadconfig().
45
+ Added getcfg() type checking.
46
+ Documentation touch for logging formats in config file.
47
+ Improved snd_notif failure logging.
48
+ Added email/notif send retries.
49
+ Added resourcelock module.
50
+ - 2.0.1 230222 - deploy_files() fix for files from package
51
+ - 2.0 230208 - Refactored and converted to installed package. Renamed funcs3 to cjnfuncs.
52
+ - ...
53
+ - 0.1 180524 - New. First github posting
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "cjnfuncs"
8
- version = "2.0.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,7 +14,9 @@ license = {file = "LICENSE.txt"}
14
14
  dependencies = [
15
15
  'requests',
16
16
  'appdirs >= 1.4',
17
- 'importlib_resources' #; python_version < "3.9"', # in 2.0.1, used for all python versions
17
+ 'dkimpy',
18
+ 'importlib_resources', #; python_version < "3.9"', # in 2.0.1, used for all python versions
19
+ 'posix-ipc >= 1.1.1'
18
20
  ]
19
21
  classifiers = [ # https://pypi.org/classifiers/
20
22
  "Topic :: Software Development :: Libraries :: Python Modules",
@@ -23,3 +25,7 @@ classifiers = [ # https://pypi.org/classifiers/
23
25
 
24
26
  [project.urls]
25
27
  repository = "https://github.com/cjnaz/cjnfuncs"
28
+
29
+
30
+ [project.scripts]
31
+ resourcelock = "cjnfuncs.resourcelock:cli"
@@ -0,0 +1,371 @@
1
+ #!/usr/bin/env python3
2
+ """cjnfuncs.SMTP - Send text message notifications and emails
3
+ """
4
+
5
+ #==========================================================
6
+ #
7
+ # Chris Nelson, 2018-2023
8
+ #
9
+ #==========================================================
10
+
11
+ import time
12
+ import smtplib
13
+ from email.mime.text import MIMEText
14
+ from email.utils import formatdate
15
+ from pathlib import Path
16
+ import dkim
17
+
18
+ from .core import logging, SndEmailError
19
+ from .mungePath import mungePath
20
+ from .timevalue import timevalue
21
+ import cjnfuncs.core as core
22
+
23
+ # Configs / Constants
24
+ SND_EMAIL_NTRIES = 3 # Number of tries to send email before aborting
25
+ SND_EMAIL_WAIT = '2s' # seconds between retries, and server connection timeout
26
+
27
+
28
+ #=====================================================================================
29
+ #=====================================================================================
30
+ # s n d _ n o t i f
31
+ #=====================================================================================
32
+ #=====================================================================================
33
+
34
+ def snd_notif(subj='Notification message', msg='', to='NotifList', log=False, smtp_config=None):
35
+ """
36
+ ## snd_notif (subj='Notification message', msg=' ', to='NotifList', log=False, smtp_config=None) - Send a text message using info from the config file
37
+
38
+ Intended for use of your mobile provider's email-to-text bridge email address, eg,
39
+ `5405551212@vzwtxt.com` for Verizon, but any email address will work.
40
+
41
+ The `to` string may be the name of a config param (who's value is one or more email addresses, default
42
+ "NotifList"), or a string with one or more email addresses. Using a config param name allows for customizing the
43
+ `to` addresses without having to edit the code.
44
+
45
+ The message to send is passed in the `msg` parameter as a text string.
46
+ Three attempts are made to send the message.
47
+
48
+
49
+ ### Parameters
50
+ `subj` (default 'Notification message')
51
+ - Text message subject field
52
+ - Some SMS/MMS apps display the subj field in bold, some in raw form, and some not at all.
53
+
54
+ `msg` (default ' ')
55
+ - Text message body
56
+
57
+ `to` (default 'NotifList')
58
+ - To whom to send the message. `to` may be either an explicit string list of email addresses
59
+ (whitespace or comma separated) or a config param name (also listing one
60
+ or more whitespace or comma separated email addresses). If the `to` parameter does not
61
+ contain an '@' it is assumed to be a config param.
62
+ - Define `NotifList` in the config file to use the default `to` value.
63
+
64
+ `log` (default False)
65
+ - If True, logs that the message was sent at the WARNING level. If False, logs
66
+ at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
67
+ The `subj` field is part of the log message.
68
+
69
+ `smtp_config` (required)
70
+ - config_item class instance containing the [SMTP] section and related params
71
+
72
+
73
+ ### cfg dictionary params in the [SMTP] section, in addition to the cfg dictionary params required for snd_email
74
+ `NotifList` (optional)
75
+ - string list of email addresses (whitespace or comma separated).
76
+ - Defining `NotifList` in the config is only required if any call to `snd_notif()` uses this
77
+ default `to` parameter value.
78
+
79
+ `DontNotif` (default False)
80
+ - If True, notification messages are not sent. Useful for debug. All email and notification
81
+ messages are also blocked if `DontEmail` is True.
82
+
83
+
84
+
85
+
86
+ ### Returns
87
+ - NoneType
88
+ - Raises `SndEmailError` on error
89
+
90
+
91
+ ### Behaviors and rules
92
+ - `snd_notif()` uses `snd_email()` to send the message. See `snd_email()` for related setup.
93
+ """
94
+
95
+ if smtp_config.getcfg('DontNotif', fallback=False, section='SMTP') or smtp_config.getcfg('DontEmail', fallback=False, section='SMTP'):
96
+ if log:
97
+ logging.warning (f"Notification NOT sent <{subj}> <{msg}>")
98
+ else:
99
+ logging.debug (f"Notification NOT sent <{subj}> <{msg}>")
100
+ return
101
+
102
+ try:
103
+ snd_email (subj=subj, body=msg, to=to, smtp_config=smtp_config)
104
+ if log:
105
+ logging.warning (f"Notification sent <{subj}> <{msg}>")
106
+ else:
107
+ logging.debug (f"Notification sent <{subj}> <{msg}>")
108
+ except Exception as e:
109
+ logging.warning (f"Notification send failed <{subj}> <{msg}>")
110
+ raise e
111
+
112
+
113
+ #=====================================================================================
114
+ #=====================================================================================
115
+ # s n d _ e m a i l
116
+ #=====================================================================================
117
+ #=====================================================================================
118
+
119
+ def snd_email(subj, to, body=None, filename=None, htmlfile=None, log=False, smtp_config=None):
120
+ """
121
+ ## 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
122
+
123
+ The `to` string may be the name of a config param (who's value is one or more email addresses),
124
+ or a string with one or more email addresses. Using a config param name allows for customizing the
125
+ `to` addresses without having to edit the code.
126
+
127
+ What to send may be a `body` string, the text contents of `filename`, or the HTML-formatted contents
128
+ of `htmlfile`, in this order of precedent. MIME multi-part is not supported.
129
+
130
+ DKIM signing is optionally supported.
131
+
132
+ Three attempts are made to send the message (see `EmailNTries`, below).
133
+
134
+
135
+ ### Parameters
136
+ `subj`
137
+ - Email subject text
138
+
139
+ `to`
140
+ - To whom to send the message. `to` may be either an explicit string list of email addresses
141
+ (whitespace or comma separated) or a config param name in the [SMTP] section (also listing one
142
+ or more whitespace or comma separated email addresses). If the `to` parameter does not
143
+ contain an '@' it is assumed to be a config param.
144
+
145
+ `body` (default None)
146
+ - A string message to be sent
147
+
148
+ `filename` (default None)
149
+ - A str or Path to the file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
150
+
151
+ `htmlfile` (default None)
152
+ - A str or Path to the html formatted file to be sent, relative to the `core.tool.cache_dir`, or an absolute path.
153
+
154
+ `log` (default False)
155
+ - If True, logs that the message was sent at the WARNING level. If False, logs
156
+ at the DEBUG level. Useful for eliminating separate logging messages in the tool script code.
157
+ The `subj` field is part of the log message.
158
+
159
+ `smtp_config` (required)
160
+ - config_item class instance containing the [SMTP] section and related params
161
+
162
+
163
+ ### cfg dictionary params in the [SMTP] section
164
+ `EmailFrom`
165
+ - An email address, such as `me@myserver.com`
166
+
167
+ `EmailServer`
168
+ - The SMTP server name, such as `mail.myserver.com`
169
+
170
+ `EmailServerPort`
171
+ - The SMTP server port (one of `P25`, `P465`, `P587`, or `P587TLS`)
172
+
173
+ `EmailUser`
174
+ - Username for `EmailServer` login, if required by the server
175
+
176
+ `EmailPass`
177
+ - Password for `EmailServer` login, if required by the server
178
+
179
+ `DontEmail` (default False)
180
+ - If True, messages are not sent. Useful for debug. Also blocks `snd_notif()` messages.
181
+
182
+ `EmailVerbose` (default False)
183
+ - If True, detailed transactions with the SMTP server are sent to stdout. Useful for debug.
184
+
185
+ `EmailNTries` (type int, default 3)
186
+ - Number of tries to send email before aborting
187
+
188
+ `EmailRetryWait` (seconds, type int, float, or timevalue, default 2s)
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'
203
+
204
+
205
+ ### Returns
206
+ - NoneType
207
+ - Raises SndEmailError on error
208
+
209
+
210
+ ### Behaviors and rules
211
+ - One of `body`, `filename`, or `htmlfile` must be specified. Looked for in this order, and the first
212
+ found is used.
213
+ - EmailServerPort must be one of the following:
214
+ - P25: SMTP to port 25 without any encryption
215
+ - P465: SMTP_SSL to port 465
216
+ - P587: SMTP to port 587 without any encryption
217
+ - P587TLS: SMTP to port 587 and with TLS encryption
218
+ - It is recommended (not required) that the email server params be placed in a user-read-only
219
+ file in the user's home directory, such as `~/creds_SMTP`, and imported by the main config file.
220
+ Some email servers require that the `EmailFrom` address be of the same domain as the server,
221
+ so it may be practical to bundle `EmailFrom` with the server specifics. Place all of these in
222
+ `~/creds_SMTP`:
223
+ - `EmailFrom`, `EmailServer`, `EmailServerPort`, `EmailUser`, and `EmailPass`
224
+ - If DKIM signing is used, also include `EmailDKIMDomain`, `EmailDKIMPem`, and `EmailDKIMSelector`
225
+ - `snd_email()` does not support multi-part MIME (an html send wont have a plain text part).
226
+ - Checking the validity of email addresses is very basic... an email address must contain an '@'.
227
+ """
228
+
229
+ if smtp_config is None:
230
+ raise SndEmailError ("smtp_section required for SMTP params")
231
+
232
+ # Deal with what to send
233
+ if body:
234
+ msg_type = "plain"
235
+ m_text = body
236
+
237
+ elif filename:
238
+ xx = mungePath(filename, core.tool.cache_dir)
239
+ try:
240
+ msg_type = "plain"
241
+ with Path.open(xx.full_path) as ifile:
242
+ m_text = ifile.read()
243
+ except Exception as e:
244
+ raise SndEmailError (f"snd_email - Message subject <{subj}>: Failed to load <{xx.full_path}>.\n {e}") from None
245
+
246
+ elif htmlfile:
247
+ xx = mungePath(htmlfile, core.tool.cache_dir)
248
+ try:
249
+ msg_type = "html"
250
+ with Path.open(xx.full_path) as ifile:
251
+ m_text = ifile.read()
252
+ except Exception as e:
253
+ raise SndEmailError (f"snd_email - Message subject <{subj}>: Failed to load <{xx.full_path}>.\n {e}") from None
254
+
255
+ else:
256
+ raise SndEmailError (f"snd_email - Message subject <{subj}>: No body, filename, or htmlfile specified.")
257
+ m_text += f"\n(sent {time.asctime(time.localtime())})"
258
+
259
+ # Deal with 'to'
260
+ def extract_email_addresses(addresses):
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}>.")
281
+
282
+ # Gather, check remaining config params
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()
288
+ if cfg_port not in ['p25', 'p465', 'p587', 'p587tls']:
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
292
+ if email_user:
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")
303
+
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
+ # Send the message, with retries
313
+ for trynum in range(ntries):
314
+ try:
315
+ msg = MIMEText(m_text, msg_type)
316
+ msg['Subject'] = subj
317
+ msg['From'] = email_from
318
+ msg['To'] = ", ".join(To)
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}>")
333
+ if cfg_port == "p25":
334
+ server = smtplib.SMTP(cfg_server, 25, timeout=retry_wait)
335
+ elif cfg_port == "p465":
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)
339
+
340
+ if smtp_config.getcfg("EmailVerbose", False, types=[bool], section='SMTP'):
341
+ logging.debug ("Set SMTP connection debuglevel(1)")
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}>")
354
+ server.sendmail(email_from, To, msg.as_string())
355
+ server.quit()
356
+
357
+ if log:
358
+ logging.warning (f"Email sent <{subj}>")
359
+ else:
360
+ logging.debug (f"Email sent <{subj}>")
361
+ return
362
+
363
+ except Exception as e:
364
+ last_error = e
365
+ if logging.getLogger().level == logging.DEBUG:
366
+ logging.exception(f"Email send try {trynum} failed:")
367
+ if trynum < ntries -1:
368
+ time.sleep(retry_wait)
369
+ continue
370
+
371
+ raise SndEmailError (f"snd_email: Send failed for <{subj}>:\n <{last_error}>")