Cette révision appartient à :
@@ -0,0 +1,68 @@
|
|||||||
|
name: Build and Push Docker Image
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test-and-build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Python setup for tests
|
||||||
|
# -----------------------------
|
||||||
|
- name: Setup Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.11'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install -r requirements.txt
|
||||||
|
pip install pytest
|
||||||
|
|
||||||
|
- name: Run tests (TEST_MODE)
|
||||||
|
env:
|
||||||
|
TEST_MODE: "true"
|
||||||
|
PYTHONPATH: .
|
||||||
|
run: |
|
||||||
|
pytest -v
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Docker login
|
||||||
|
# -----------------------------
|
||||||
|
- name: Login to Gitea Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ vars.REGISTRY_URL }}
|
||||||
|
username: ${{ vars.REGISTRY_USERNAME }}
|
||||||
|
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Docker metadata
|
||||||
|
# -----------------------------
|
||||||
|
- name: Extract metadata
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ vars.REGISTRY_URL }}/mail2sms
|
||||||
|
tags: |
|
||||||
|
type=raw,value=latest
|
||||||
|
type=sha
|
||||||
|
|
||||||
|
# -----------------------------
|
||||||
|
# Build & Push (only if tests passed)
|
||||||
|
# -----------------------------
|
||||||
|
- name: Build and Push
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ vars.REGISTRY_URL }}/mail2sms:latest
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
.pytest_cache/
|
||||||
|
.env
|
||||||
|
venv/
|
||||||
|
.vscode/
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1
|
||||||
|
ENV PYTHONUNBUFFERED=1
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
gcc \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
ENV PYTHONPATH=/app
|
||||||
|
|
||||||
|
CMD ["python", "mail2sms/main.py"]
|
||||||
+201
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2026 Jimmy GALLAND
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
+146
@@ -0,0 +1,146 @@
|
|||||||
|
# 📬 Mail2SMS
|
||||||
|
|
||||||
|
A production-ready Mail-to-SMS gateway.
|
||||||
|
|
||||||
|
This service monitors an IMAP inbox in real-time (IMAP IDLE) and sends SMS messages through an external SMS API: sms-gate private server https://sms-gate.app
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Features
|
||||||
|
|
||||||
|
- 📡 Real-time IMAP IDLE monitoring
|
||||||
|
- 🔄 Automatic reconnection handling
|
||||||
|
- 📤 SMS sending via HTTP API (Basic Auth)
|
||||||
|
- 🧠 Dynamic subject parameter parsing
|
||||||
|
- 📧 Status email feedback
|
||||||
|
- 🐳 Docker-ready
|
||||||
|
- ⚙ Environment-based configuration
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🧩 How It Works
|
||||||
|
|
||||||
|
An email must contain parameters in the **subject line**:
|
||||||
|
|
||||||
|
```
|
||||||
|
to=+33612345678 deviceId=ABC123 simNumber=2
|
||||||
|
```
|
||||||
|
|
||||||
|
### Supported Subject Parameters
|
||||||
|
|
||||||
|
| Parameter | Required | Description |
|
||||||
|
|------------|----------|-------------|
|
||||||
|
| `to` | ✅ Yes | Destination phone number (E.164 format) |
|
||||||
|
| `deviceId` | ❌ No | SMS gateway device ID |
|
||||||
|
| `simNumber`| ❌ No | SIM slot number |
|
||||||
|
| `login` | ❌ No | login/username API |
|
||||||
|
| `password` | ❌ No | password API |
|
||||||
|
|
||||||
|
If 'deviceId' or 'simNumber' are not provided, then try using the environment variables, and otherwise don't pass them to the API which will take automatic values.
|
||||||
|
|
||||||
|
# 🛠 Installation
|
||||||
|
|
||||||
|
## 1️⃣ Clone the repository
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.celjim.fr/jimmyGALLAND/mail2sms.git
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2️⃣ Create environment file
|
||||||
|
|
||||||
|
Create a `.env` file:
|
||||||
|
|
||||||
|
```env
|
||||||
|
### Required ###
|
||||||
|
IMAP_SERVER=imap.example.com
|
||||||
|
EMAIL_ACCOUNT=mail@example.com
|
||||||
|
EMAIL_PASSWORD=yourpassword
|
||||||
|
SMTP_SERVER=smtp.example.com
|
||||||
|
API_URL=https://api.sms-gateway.com/3rdparty/v1/message
|
||||||
|
|
||||||
|
### Optional ###
|
||||||
|
API_USERNAME=apiuser
|
||||||
|
API_PASSWORD=apipassword
|
||||||
|
DEFAULT_DEVICE_ID=XXXXXXXX
|
||||||
|
DEFAULT_SIM_NUMBER=1
|
||||||
|
IMAP_PORT=993
|
||||||
|
SMTP_PORT=587
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🐳 Docker Deployment
|
||||||
|
|
||||||
|
## Build Docker image
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd mail2sms
|
||||||
|
docker build -t mail2sms:latest .
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run container
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d \
|
||||||
|
--name mail2sms \
|
||||||
|
--env-file .env \
|
||||||
|
--restart unless-stopped \
|
||||||
|
mail2sms:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🔁 Updating the Service
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git pull
|
||||||
|
docker build -t mail2sms:latest .
|
||||||
|
docker stop mail2sms
|
||||||
|
docker rm mail2sms
|
||||||
|
docker run -d --name mail2sms --env-file .env --restart unless-stopped mail2sms:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 📧 Email Usage Example
|
||||||
|
|
||||||
|
### Subject:
|
||||||
|
```
|
||||||
|
to=+33612345678 [login=yourApiLogin password=yourApiPssword deviceId=ABC123 simNumber=2]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Body:
|
||||||
|
```
|
||||||
|
Hello from Mail2SMS!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 🛡 Production Notes
|
||||||
|
|
||||||
|
- Uses persistent IMAP connection (IDLE mode)
|
||||||
|
- Auto-reconnects on network failure
|
||||||
|
- Handles SMTP/API timeouts
|
||||||
|
- Safe for long-running container environments
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 📊 Improvements envisaged in the future
|
||||||
|
|
||||||
|
- Healthcheck route for Docker
|
||||||
|
- Webhook support for delivery confirmation
|
||||||
|
- Rate limiting and retry backoff
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 📜 License
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
[Read Licence](https://git.celjim.fr/jimmyGALLAND/mail2sms/src/LICENSE)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 👤 Author
|
||||||
|
Jimmy GALLAND
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
### Required ###
|
||||||
|
IMAP_SERVER=imap.example.com
|
||||||
|
EMAIL_ACCOUNT=yourImapLogin
|
||||||
|
EMAIL_PASSWORD=yourImapPassword
|
||||||
|
API_URL=https://api.sms-gateway.com/3rdparty/v1/message
|
||||||
|
SMTP_SERVER=smtp.example.com
|
||||||
|
|
||||||
|
### Optional ###
|
||||||
|
#IMAP_PORT=993
|
||||||
|
#SMTP_PORT=587
|
||||||
|
#API_USERNAME=apiUser
|
||||||
|
#API_PASSWORD=apiPassword
|
||||||
|
#DEFAULT_DEVICE_ID=idDevice
|
||||||
|
#DEFAULT_SIM_NUMBER=simNumber
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
import os
|
||||||
|
import time
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import requests
|
||||||
|
import smtplib
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from imapclient import IMAPClient
|
||||||
|
from requests.auth import HTTPBasicAuth
|
||||||
|
from .text_utils import html_to_sms_text
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# CONFIGURATION
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
IMAP_SERVER = os.getenv("IMAP_SERVER")
|
||||||
|
IMAP_PORT = int(os.getenv("IMAP_PORT", 993))
|
||||||
|
EMAIL_ACCOUNT = os.getenv("EMAIL_ACCOUNT")
|
||||||
|
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
|
||||||
|
|
||||||
|
SMTP_SERVER = os.getenv("SMTP_SERVER")
|
||||||
|
SMTP_PORT = int(os.getenv("SMTP_PORT", 587))
|
||||||
|
|
||||||
|
API_URL = os.getenv("API_URL")
|
||||||
|
|
||||||
|
API_USERNAME = os.getenv("API_USERNAME")
|
||||||
|
API_PASSWORD = os.getenv("API_PASSWORD")
|
||||||
|
|
||||||
|
DEFAULT_DEVICE_ID = os.getenv("DEFAULT_DEVICE_ID")
|
||||||
|
DEFAULT_SIM_NUMBER = os.getenv("DEFAULT_SIM_NUMBER")
|
||||||
|
|
||||||
|
IDLE_TIMEOUT = 60 * 25 # 25 minutes (safe before typical 30 min timeout)
|
||||||
|
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# LOGGING
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
def log(message):
|
||||||
|
print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {message}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def html_to_sms_text(raw_html):
|
||||||
|
"""
|
||||||
|
Convert HTML content to clean SMS-compatible plain text.
|
||||||
|
- Removes HTML tags
|
||||||
|
- Decodes HTML entities
|
||||||
|
- Normalizes unicode
|
||||||
|
- Removes unsupported SMS characters
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not raw_html:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Parse HTML
|
||||||
|
soup = BeautifulSoup(raw_html, "html.parser")
|
||||||
|
|
||||||
|
# Get text only
|
||||||
|
text = soup.get_text(separator=" ")
|
||||||
|
|
||||||
|
# Decode HTML entities ( & etc.)
|
||||||
|
text = html.unescape(text)
|
||||||
|
|
||||||
|
# Normalize unicode (remove weird accents/combined chars)
|
||||||
|
text = unicodedata.normalize("NFKD", text)
|
||||||
|
|
||||||
|
# Remove non GSM basic characters
|
||||||
|
gsm_basic = (
|
||||||
|
"@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ"
|
||||||
|
+ ' !"#¤%&\'()*+,-./'
|
||||||
|
+ "0123456789:;<=>?"
|
||||||
|
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
+ "ÄÖÑܧ¿"
|
||||||
|
+ "abcdefghijklmnopqrstuvwxyz"
|
||||||
|
+ "äöñüà"
|
||||||
|
)
|
||||||
|
|
||||||
|
cleaned = "".join(c for c in text if c in gsm_basic)
|
||||||
|
|
||||||
|
# Remove multiple spaces
|
||||||
|
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
||||||
|
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# SUBJECT PARAMETER EXTRACTION
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
def extract_parameters(subject):
|
||||||
|
"""
|
||||||
|
Extract parameters from email subject.
|
||||||
|
Returns: to, device_id, sim_number, api_login, api_password
|
||||||
|
"""
|
||||||
|
if not subject:
|
||||||
|
return None, None, None, None, None
|
||||||
|
|
||||||
|
# Regex case-insensitive
|
||||||
|
def get_param(name):
|
||||||
|
match = re.search(rf"{name}\s*=\s*([^; ]+)", subject, re.IGNORECASE)
|
||||||
|
return match.group(1) if match else None
|
||||||
|
|
||||||
|
to = get_param("to")
|
||||||
|
device_id = get_param("deviceId")
|
||||||
|
sim_number = get_param("simNumber")
|
||||||
|
api_login = get_param("login")
|
||||||
|
api_password = get_param("password")
|
||||||
|
|
||||||
|
return to, device_id, sim_number, api_login, api_password
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# SMS SEND
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
def send_sms(payload, username, password):
|
||||||
|
"""
|
||||||
|
Send SMS using the API.
|
||||||
|
In TEST_MODE, it returns a fake response.
|
||||||
|
If username/password are provided, they override the defaults from env.
|
||||||
|
"""
|
||||||
|
if TEST_MODE:
|
||||||
|
log("TEST_MODE enabled - Fake SMS send")
|
||||||
|
class FakeResponse:
|
||||||
|
status_code = 202
|
||||||
|
text = json.dumps({"id": "fake-id", "state": "Sent"})
|
||||||
|
return FakeResponse()
|
||||||
|
|
||||||
|
return requests.post(
|
||||||
|
API_URL,
|
||||||
|
auth=HTTPBasicAuth(username, password),
|
||||||
|
headers={"Content-Type": "application/json"},
|
||||||
|
data=json.dumps(payload),
|
||||||
|
timeout=15
|
||||||
|
)
|
||||||
|
# ============================================================
|
||||||
|
# STATUS EMAIL
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
def send_status_email(to_address, phone, status_code, response_text):
|
||||||
|
if TEST_MODE:
|
||||||
|
log("TEST_MODE enabled - Fake email send")
|
||||||
|
return
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg["From"] = EMAIL_ACCOUNT
|
||||||
|
msg["To"] = to_address
|
||||||
|
msg["Subject"] = f"SMS Status for {phone}"
|
||||||
|
msg.set_content(
|
||||||
|
f"Destination: {phone}\n"
|
||||||
|
f"HTTP Code: {status_code}\n\n"
|
||||||
|
f"API Response:\n{response_text}"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT, timeout=10) as server:
|
||||||
|
server.starttls()
|
||||||
|
server.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
|
||||||
|
server.send_message(msg)
|
||||||
|
log(f"Status email sent to {to_address}")
|
||||||
|
except Exception as e:
|
||||||
|
log(f"SMTP error: {e}")
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# PROCESS EMAILS READING
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
def process_unseen(server):
|
||||||
|
messages = server.search(['UNSEEN'])
|
||||||
|
if not messages:
|
||||||
|
return
|
||||||
|
log(f"{len(messages)} new message(s) detected")
|
||||||
|
fetched = server.fetch(messages, ['RFC822'])
|
||||||
|
for uid, message_data in fetched.items():
|
||||||
|
try:
|
||||||
|
import email
|
||||||
|
msg = email.message_from_bytes(message_data[b'RFC822'])
|
||||||
|
sender = email.utils.parseaddr(msg["From"])[1]
|
||||||
|
subject = msg["Subject"]
|
||||||
|
phone_number, subject_device_id, subject_sim_number, api_login, api_password = extract_parameters(subject)
|
||||||
|
|
||||||
|
if not phone_number:
|
||||||
|
log("No phone number found in subject")
|
||||||
|
server.add_flags(uid, ['\\Seen'])
|
||||||
|
continue
|
||||||
|
device_id = subject_device_id or DEFAULT_DEVICE_ID
|
||||||
|
sim_number = subject_sim_number or DEFAULT_SIM_NUMBER
|
||||||
|
username = api_login or API_USERNAME
|
||||||
|
if not username:
|
||||||
|
log("No API Username found")
|
||||||
|
server.add_flags(uid, ['\\Seen'])
|
||||||
|
continue
|
||||||
|
password = api_password or API_PASSWORD
|
||||||
|
if not password:
|
||||||
|
log("No API Password found")
|
||||||
|
server.add_flags(uid, ['\\Seen'])
|
||||||
|
continue
|
||||||
|
|
||||||
|
sms_text = ""
|
||||||
|
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
content_type = part.get_content_type()
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
|
||||||
|
if not payload:
|
||||||
|
continue
|
||||||
|
|
||||||
|
decoded = payload.decode(errors="ignore")
|
||||||
|
|
||||||
|
if content_type == "text/plain":
|
||||||
|
sms_text = decoded.strip()
|
||||||
|
break
|
||||||
|
|
||||||
|
elif content_type == "text/html" and not sms_text:
|
||||||
|
sms_text = html_to_sms_text(decoded)
|
||||||
|
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload:
|
||||||
|
decoded = payload.decode(errors="ignore")
|
||||||
|
if msg.get_content_type() == "text/html":
|
||||||
|
sms_text = html_to_sms_text(decoded)
|
||||||
|
else:
|
||||||
|
sms_text = decoded.strip()
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"textMessage": {"text": sms_text},
|
||||||
|
"phoneNumbers": [phone_number]
|
||||||
|
}
|
||||||
|
if device_id:
|
||||||
|
payload["deviceId"] = device_id
|
||||||
|
if sim_number:
|
||||||
|
payload["simNumber"] = int(sim_number)
|
||||||
|
log(f"Sending SMS to {phone_number} using deviceId={device_id} simNumber={sim_number}")
|
||||||
|
response = send_sms(payload, username, password)
|
||||||
|
log(f"HTTP {response.status_code}")
|
||||||
|
send_status_email(sender, phone_number, response.status_code, response.text)
|
||||||
|
if 200 <= response.status_code <= 204:
|
||||||
|
server.delete_messages(uid)
|
||||||
|
log("Email deleted (success)")
|
||||||
|
else:
|
||||||
|
server.add_flags(uid, ['\\Seen'])
|
||||||
|
log("Email kept (non-success response)")
|
||||||
|
except Exception as e:
|
||||||
|
log(f"Processing error: {e}")
|
||||||
|
server.add_flags(uid, ['\\Seen'])
|
||||||
|
server.expunge()
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# HANDLE IMAP CONNECTION
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
def connect():
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
log("Connecting to IMAP server...")
|
||||||
|
server = IMAPClient(IMAP_SERVER, port=IMAP_PORT, ssl=True, timeout=20)
|
||||||
|
server.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
|
||||||
|
server.select_folder("INBOX")
|
||||||
|
log("IMAP connected successfully")
|
||||||
|
return server
|
||||||
|
except (socket.error, Exception) as e:
|
||||||
|
log(f"IMAP connection failed: {e}")
|
||||||
|
time.sleep(10)
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# IDLE LOOP
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
def idle_loop():
|
||||||
|
server = connect()
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
log("Entering IDLE mode")
|
||||||
|
server.idle()
|
||||||
|
responses = server.idle_check(timeout=IDLE_TIMEOUT)
|
||||||
|
server.idle_done()
|
||||||
|
if responses:
|
||||||
|
log("New mail event received")
|
||||||
|
process_unseen(server)
|
||||||
|
else:
|
||||||
|
log("Idle timeout reached (keep-alive)")
|
||||||
|
except (socket.error, Exception) as e:
|
||||||
|
log(f"Connection lost: {e}")
|
||||||
|
try:
|
||||||
|
server.logout()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
time.sleep(5)
|
||||||
|
server = connect()
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# ENTRY POINT
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
log("Mail2SMS service started")
|
||||||
|
if TEST_MODE:
|
||||||
|
log("Running in TEST_MODE - no IMAP connection")
|
||||||
|
else:
|
||||||
|
idle_loop()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import re
|
||||||
|
import html
|
||||||
|
import unicodedata
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
|
||||||
|
|
||||||
|
def html_to_sms_text(raw_html: str) -> str:
|
||||||
|
"""
|
||||||
|
Convert HTML content to clean SMS-compatible plain text.
|
||||||
|
- Removes HTML tags
|
||||||
|
- Decodes HTML entities
|
||||||
|
- Normalizes unicode
|
||||||
|
- Removes unsupported GSM characters
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not raw_html:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Parse HTML
|
||||||
|
soup = BeautifulSoup(raw_html, "html.parser")
|
||||||
|
text = soup.get_text(separator=" ")
|
||||||
|
|
||||||
|
# Decode HTML entities
|
||||||
|
text = html.unescape(text)
|
||||||
|
|
||||||
|
# Normalize unicode
|
||||||
|
text = unicodedata.normalize("NFKD", text)
|
||||||
|
|
||||||
|
# GSM basic charset
|
||||||
|
gsm_basic = (
|
||||||
|
"@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ"
|
||||||
|
+ ' !"#¤%&\'()*+,-./'
|
||||||
|
+ "0123456789:;<=>?"
|
||||||
|
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
+ "ÄÖÑܧ¿"
|
||||||
|
+ "abcdefghijklmnopqrstuvwxyz"
|
||||||
|
+ "äöñüà"
|
||||||
|
)
|
||||||
|
|
||||||
|
cleaned = "".join(c for c in text if c in gsm_basic)
|
||||||
|
|
||||||
|
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
||||||
|
|
||||||
|
return cleaned
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
requests
|
||||||
|
imapclient
|
||||||
|
beautifulsoup4
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import json
|
||||||
|
import pytest
|
||||||
|
import os
|
||||||
|
from mail2sms.main import extract_parameters, send_sms, TEST_MODE
|
||||||
|
|
||||||
|
# ------------------------------
|
||||||
|
# TEST: Params extract
|
||||||
|
# ------------------------------
|
||||||
|
|
||||||
|
def test_extract_full_parameters():
|
||||||
|
subject = "Login=myuser;Password=mypass;To=+33612345678;deviceId=ABC123;simNumber=2"
|
||||||
|
to, device, sim, login, passwd = extract_parameters(subject)
|
||||||
|
assert to == "+33612345678"
|
||||||
|
assert device == "ABC123"
|
||||||
|
assert sim == "2"
|
||||||
|
assert login == "myuser"
|
||||||
|
assert passwd == "mypass"
|
||||||
|
|
||||||
|
def test_extract_partial_parameters():
|
||||||
|
subject = "to=+33612345678;Login=apiuser;Password=apipass"
|
||||||
|
to, device, sim, login, passwd = extract_parameters(subject)
|
||||||
|
assert to == "+33612345678"
|
||||||
|
assert device is None
|
||||||
|
assert sim is None
|
||||||
|
assert login == "apiuser"
|
||||||
|
assert passwd == "apipass"
|
||||||
|
|
||||||
|
def test_extract_case_insensitive():
|
||||||
|
subject = "login=USER;password=PASS;to=+33600000000;deviceId=Dev1;simNumber=1"
|
||||||
|
to, device, sim, login, passwd = extract_parameters(subject)
|
||||||
|
assert to == "+33600000000"
|
||||||
|
assert device == "Dev1"
|
||||||
|
assert sim == "1"
|
||||||
|
assert login == "USER"
|
||||||
|
assert passwd == "PASS"
|
||||||
|
|
||||||
|
def test_extract_invalid_subject():
|
||||||
|
subject = "hello world"
|
||||||
|
to, device, sim, login, passwd = extract_parameters(subject)
|
||||||
|
assert to is None
|
||||||
|
assert device is None
|
||||||
|
assert sim is None
|
||||||
|
assert login is None
|
||||||
|
assert passwd is None
|
||||||
|
|
||||||
|
# ------------------------------
|
||||||
|
# TEST: fake SMS send
|
||||||
|
# ------------------------------
|
||||||
|
|
||||||
|
def test_fake_sms_send(monkeypatch):
|
||||||
|
monkeypatch.setenv("TEST_MODE", "true")
|
||||||
|
payload = {"textMessage": {"text": "Hello world"}, "phoneNumbers": ["+33612345678"]}
|
||||||
|
response = send_sms(payload, username="fakeuser", password="fakepass")
|
||||||
|
assert response.status_code == 202
|
||||||
|
resp_json = json.loads(response.text)
|
||||||
|
assert resp_json["state"] == "Sent"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import pytest
|
||||||
|
from mail2sms.text_utils import html_to_sms_text
|
||||||
|
|
||||||
|
|
||||||
|
def test_html_cleaning():
|
||||||
|
html = "<h1>Hello</h1><p>World <strong>123</strong></p>"
|
||||||
|
result = html_to_sms_text(html)
|
||||||
|
assert result == "Hello World 123"
|
||||||
Référencer dans un nouveau ticket
Bloquer un utilisateur