multi_notifier 0.6.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.
@@ -0,0 +1,33 @@
1
+ name: Publish Python Package
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ publish:
10
+ runs-on: ubuntu-latest
11
+ environment:
12
+ name: pypi
13
+ permissions:
14
+ id-token: write
15
+ contents: read
16
+ steps:
17
+ - name: Check out code
18
+ uses: actions/checkout@v6
19
+
20
+ - name: Checkout
21
+ uses: actions/checkout@v6
22
+
23
+ - name: Install uv
24
+ uses: astral-sh/setup-uv@v7
25
+
26
+ - name: Install Python 3.13
27
+ run: uv python install 3.13
28
+
29
+ - name: Build
30
+ run: uv build
31
+
32
+ - name: Publish
33
+ run: uv publish
@@ -0,0 +1,40 @@
1
+ name: Run Tests
2
+
3
+ on:
4
+ pull_request:
5
+ workflow_dispatch:
6
+
7
+ jobs:
8
+ pre-commit:
9
+ runs-on: ubuntu-latest
10
+ strategy:
11
+ fail-fast: false
12
+ matrix:
13
+ python-version:
14
+ - "3.11"
15
+ - "3.12"
16
+ - "3.13"
17
+ - "3.14"
18
+
19
+ steps:
20
+ - name: Checkout Code
21
+ uses: actions/checkout@v6
22
+
23
+ - name: Install uv and set the Python version
24
+ uses: astral-sh/setup-uv@v7
25
+ with:
26
+ python-version: ${{ matrix.python-version }}
27
+
28
+ - name: Install the project
29
+ run: uv sync --frozen --all-groups
30
+
31
+ - name: Run Prek Hooks
32
+ run: |
33
+ uv run prek run --all-files
34
+
35
+ - name: Upload Coverage Report
36
+ if: always()
37
+ uses: actions/upload-artifact@v7
38
+ with:
39
+ name: coverage-report-${{ matrix.python-version }}
40
+ path: htmlcov
@@ -0,0 +1,5 @@
1
+ formatter:
2
+ type: basic
3
+ eof_newline: true
4
+ max_line_length: 120
5
+ retain_line_breaks_single: true
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 N.Seuling
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: multi_notifier
3
+ Version: 0.6.0
4
+ Summary: notify multiple recipients on multiple protocols
5
+ Author: Seuling N.
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: aiogram>=3.27.0
10
+ Requires-Dist: pydantic<3.0.0,>=2.6.0
11
+ Requires-Dist: pyyaml~=6.0
12
+ Requires-Dist: sulguk>=0.11.1
@@ -0,0 +1,64 @@
1
+ # Version 0.6.0 - 09.04.2026
2
+
3
+ ## Breaking Changes
4
+
5
+ - renamed Exceptions to Error
6
+ - removed `connector_mail_imap`
7
+ - removed `send_handler`
8
+
9
+ # Features
10
+
11
+ - refactored `multi_notifier.connector_mail.Mail` connector to use `email` package (built-in python library)
12
+ - added possibility to send images and html with `multi_notifier.connector_telegram.Telegram`
13
+ - changed to new project structure with pyproject.toml and modern tools like ruff / prek
14
+
15
+ # Version 0.5.0 - 03.08.2024
16
+
17
+ ## Features
18
+
19
+ - bumped versions:
20
+ - requests~=2.32.0
21
+ - pydantic>=2.6.0,\<3.0.0
22
+
23
+ # Version 0.4.0 - 19.03.2024
24
+
25
+ ## Breaking Change
26
+
27
+ - changed `smtp_server` to `smtp_host`
28
+
29
+ ## Features
30
+
31
+ - refactored config of all connectors to use pydantic validation.
32
+
33
+ # Version 0.3.0 - 16.03.2024
34
+
35
+ ## Breaking Change
36
+
37
+ - the mail connector `multi_notifier.connectors.connector_mail` was replaced by a connector which only can send mail. If the IMAP features are needed the following class must be used: `multi_notifier.connectors.connector_mail_imap`
38
+
39
+ ## Features
40
+
41
+ - changed mail to use the `redmail` package
42
+
43
+ # Version 0.2.3 - 12.03.2024
44
+
45
+ ## Bugfix
46
+
47
+ - fixed bug in `multinotifier.conectors.connector_mail.Mail` which prevents sending multiple mails with a large interval
48
+
49
+ # Version 0.2.2 - 26.09.2023
50
+
51
+ ## General
52
+
53
+ - switched to nose_helper python package
54
+
55
+ ## Bugfix
56
+
57
+ - fixed bug which caused a complete crash if one connector could not be initialized
58
+
59
+ # Version 0.2.1 - 30.10.2022
60
+
61
+ ## Bugfix
62
+
63
+ - fixed bug which caused a crash if called from debugger
64
+ - added timeout to telegram calls
@@ -0,0 +1,3 @@
1
+ """Init file of send_handler."""
2
+
3
+ __version__ = "0.6.0"
@@ -0,0 +1 @@
1
+ """Init file of all connectors."""
@@ -0,0 +1,216 @@
1
+ """Connector for mail."""
2
+
3
+ import html
4
+ import logging
5
+ import re
6
+ import smtplib
7
+ import ssl
8
+ from email.charset import QP, Charset
9
+ from email.mime.image import MIMEImage
10
+ from email.mime.multipart import MIMEMultipart
11
+ from email.mime.text import MIMEText
12
+ from email.utils import formatdate, make_msgid
13
+ from pathlib import Path
14
+
15
+ import pydantic
16
+
17
+ import multi_notifier.connectors.exceptions
18
+ import multi_notifier.connectors.interface
19
+
20
+ LOGGER = logging.getLogger(__name__)
21
+
22
+
23
+ class MailConfig(pydantic.BaseModel):
24
+ """Config for mail connector."""
25
+
26
+ user: str
27
+ password: str
28
+ smtp_host: str
29
+ smtp_port: int
30
+
31
+
32
+ class Mail(multi_notifier.connectors.interface.Interface):
33
+ """Class to send e-mails."""
34
+
35
+ __html_pattern = re.compile(r"<[^<]+?>")
36
+
37
+ def __init__(self, mail_config: MailConfig) -> None:
38
+ """Init Mail class.
39
+
40
+ Args:
41
+ mail_config: config for mail connector
42
+
43
+ Raises:
44
+ multi_notifier.connectors.exceptions.ConnectorConfigurationError: If mail configuration is faulty
45
+ """
46
+ self.config = mail_config
47
+ self.smtp_host = mail_config.smtp_host
48
+ self.smtp_port = mail_config.smtp_port
49
+ self.user = mail_config.user
50
+ self.password = mail_config.password
51
+
52
+ def _create_msg(self, recipients: list[str], message: str, subject: str | None = None, images: dict[str, Path] | None = None) -> MIMEMultipart: # noqa: C901, PLR0915
53
+ """Create a MIME multipart message with optional images and HTML support.
54
+
55
+ Args:
56
+ recipients: list of recipients (email addresses).
57
+ message: Message content (plain text or HTML).
58
+ subject: Subject line of the email. Defaults to "No Subject" if not provided.
59
+ images: Dictionary mapping Content-ID to image file paths for embedded images.
60
+
61
+ Returns:
62
+ MIMEMultipart: A MIME message object ready to be sent via SMTP.
63
+
64
+ Raises:
65
+ No direct exceptions, but logs warnings if image files are not found.
66
+ """
67
+ if images is None:
68
+ images = {}
69
+
70
+ # check if content of message is HTML and set text / HTML
71
+ is_html = bool(self.__html_pattern.search(message))
72
+
73
+ # Create MIME message structure
74
+ # For emails with images and HTML:
75
+ # related - root
76
+ # └── alternative (text/html variants)
77
+ # ├── text/plain
78
+ # └── text/html
79
+ # └── image1, image2, ... (embedded images with Content-ID)
80
+ #
81
+ # For emails with images and plain text:
82
+ # mixed - root
83
+ # ├── alternative (text/plain)
84
+ # └── image1, image2, ... (regular attachments)
85
+ #
86
+ # For emails without images:
87
+ # alternative - root
88
+ # ├── text/plain
89
+ # └── text/html (if HTML)
90
+ if images and not is_html:
91
+ # Plain text with images: use multipart/mixed for regular attachments
92
+ msg = MIMEMultipart("mixed")
93
+ alternative = MIMEMultipart("alternative")
94
+ msg.attach(alternative)
95
+ elif images and is_html:
96
+ # HTML with images: use multipart/related for embedded images
97
+ msg = MIMEMultipart("related")
98
+ alternative = MIMEMultipart("alternative")
99
+ msg.attach(alternative)
100
+ else:
101
+ # No images: simple alternative structure
102
+ msg = MIMEMultipart("alternative")
103
+ # Smart alias: When no images exist, msg and alternative point to the same object.
104
+ # This allows the code below to always use "alternative.attach()" regardless
105
+ # of whether images are present or not.
106
+ alternative = msg
107
+
108
+ msg["Subject"] = subject or "No Subject"
109
+ msg["From"] = self.user
110
+ msg["MIME-Version"] = "1.0"
111
+ msg["Message-ID"] = make_msgid(domain=self.smtp_host)
112
+ msg["Date"] = formatdate(localtime=True)
113
+ msg["To"] = ", ".join(recipients)
114
+
115
+ # Add text and HTML parts with explicit UTF-8 charset
116
+ # Charset encoding: Use quoted-printable to keep emails readable and smaller than base64
117
+ charset = Charset("utf-8")
118
+ charset.header_encoding = QP
119
+ charset.body_encoding = QP
120
+ if is_html:
121
+ # Create plain text version from HTML
122
+ # This provides a fallback for email clients that don't support HTML
123
+ plain_text = self.__html_pattern.sub("", message)
124
+ # Clean up extra whitespace and decode HTML entities
125
+ plain_text = html.unescape(plain_text)
126
+ plain_text = re.sub(r"\s+", " ", plain_text).strip()
127
+
128
+ text_part = MIMEText(plain_text, "plain", _charset="utf-8")
129
+ html_part = MIMEText(message, "html", _charset="utf-8")
130
+ # Apply quoted-printable encoding for better email compatibility
131
+ text_part.set_charset(charset)
132
+ html_part.set_charset(charset)
133
+ # Attach both alternatives: email client chooses the best one it can render
134
+ alternative.attach(text_part)
135
+ alternative.attach(html_part)
136
+ else:
137
+ text_part = MIMEText(message, "plain", _charset="utf-8")
138
+ text_part.set_charset(charset)
139
+ alternative.attach(text_part)
140
+
141
+ # Add images
142
+ if is_html:
143
+ # For HTML messages: embed images with Content-ID for HTML reference
144
+ # Images are attached to the 'msg' object (the root container), not to 'alternative'.
145
+ # This ensures images are in the multipart/related structure, allowing them to be
146
+ # referenced by their Content-ID in HTML img tags: <img src="cid:image_id">
147
+ for cid, image_path in images.items():
148
+ try:
149
+ img_data = image_path.read_bytes()
150
+ img = MIMEImage(img_data)
151
+ # Set Content-ID header: allows HTML to reference this image via src="cid:..."
152
+ img.add_header("Content-ID", f"<{cid}>")
153
+ msg.attach(img)
154
+ except FileNotFoundError:
155
+ LOGGER.warning(f"Image file not found: {image_path}")
156
+ continue
157
+ elif images:
158
+ # For plain text messages: add images as regular attachments
159
+ for image_path in images.values():
160
+ try:
161
+ img_data = image_path.read_bytes()
162
+ img = MIMEImage(img_data)
163
+ # Add filename and disposition for regular attachment
164
+ filename = image_path.name
165
+ img.add_header("Content-Disposition", f'attachment; filename="{filename}"')
166
+ msg.attach(img)
167
+ except FileNotFoundError:
168
+ LOGGER.warning(f"Image file not found: {image_path}")
169
+ continue
170
+
171
+ return msg
172
+
173
+ def send_message(self, recipient: str | list[str], message: str, subject: str | None = None, images: dict[str, Path] | None = None) -> None:
174
+ """Send a message to one or multiple recipients.
175
+
176
+ Args:
177
+ recipient: one or multiple recipients. (Must be mail addresses!)
178
+ message: Message which should be sent
179
+ subject: Subject of the mail
180
+ images: Images which will be added to the mail
181
+
182
+ Raises:
183
+ multi_notifier.connectors.exceptions.ConnectorError: if mail could not be sent
184
+ """
185
+ LOGGER.debug(f"Sending mail to {recipient} with subject '{subject}' and message '{message[:20]}'")
186
+ recipient_list = recipient if isinstance(recipient, list) else [recipient]
187
+ msg = self._create_msg(recipient_list, message, subject, images)
188
+
189
+ try:
190
+ # Create SMTP session
191
+ context = ssl.create_default_context()
192
+ with smtplib.SMTP(self.smtp_host, self.smtp_port) as server:
193
+ server.starttls(context=context)
194
+ server.login(self.user, self.password)
195
+
196
+ # Send email
197
+ server.send_message(msg, to_addrs=recipient_list)
198
+
199
+ except Exception as exc:
200
+ LOGGER.exception(msg := "Could not send mail")
201
+ raise multi_notifier.connectors.exceptions.ConnectorError(msg) from exc
202
+
203
+ @staticmethod
204
+ def is_valid_recipient(recipient: str) -> bool:
205
+ """Check if the given recipient is valid.
206
+
207
+ Args:
208
+ recipient: Single recipient which should be checked
209
+
210
+ Returns:
211
+ True if recipient has a supported format, else False.
212
+ """
213
+ if re.fullmatch(r"[^@]+@[^@]+\.[^@]+", recipient):
214
+ return True
215
+ LOGGER.warning(f"The recipient '{recipient}' is not valid !")
216
+ return False