From 49ce0b554355b7a6b3de4e28a86bef3c641e1321 Mon Sep 17 00:00:00 2001 From: Raoul Snyman Date: Mon, 31 Jul 2023 22:35:39 -0700 Subject: [PATCH] Initial commit --- .flake8 | 2 ++ .gitignore | 2 ++ .woodpecker.yaml | 53 +++++++++++++++++++++++++++++++++ Dockerfile.nightly | 10 +++++++ Dockerfile.release | 6 ++++ LICENSE.txt | 9 ++++++ README.rst | 20 +++++++++++++ http2smtp/__about__.py | 4 +++ http2smtp/__init__.py | 3 ++ http2smtp/app.py | 26 +++++++++++++++++ http2smtp/message.py | 38 ++++++++++++++++++++++++ http2smtp/models.py | 10 +++++++ http2smtp/settings.py | 19 ++++++++++++ http2smtp/smtp.py | 12 ++++++++ pyproject.toml | 66 ++++++++++++++++++++++++++++++++++++++++++ tests/__init__.py | 3 ++ tests/conftest.py | 0 tests/test_message.py | 30 +++++++++++++++++++ tests/test_smtp.py | 24 +++++++++++++++ 19 files changed, 337 insertions(+) create mode 100644 .flake8 create mode 100644 .gitignore create mode 100644 .woodpecker.yaml create mode 100644 Dockerfile.nightly create mode 100644 Dockerfile.release create mode 100644 LICENSE.txt create mode 100644 README.rst create mode 100644 http2smtp/__about__.py create mode 100644 http2smtp/__init__.py create mode 100644 http2smtp/app.py create mode 100644 http2smtp/message.py create mode 100644 http2smtp/models.py create mode 100644 http2smtp/settings.py create mode 100644 http2smtp/smtp.py create mode 100644 pyproject.toml create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_message.py create mode 100644 tests/test_smtp.py diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..6deafc2 --- /dev/null +++ b/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 120 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d8a1bb0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__ +.coverage diff --git a/.woodpecker.yaml b/.woodpecker.yaml new file mode 100644 index 0000000..e3bd1cc --- /dev/null +++ b/.woodpecker.yaml @@ -0,0 +1,53 @@ +steps: + lint: + image: python:3.11 + commands: + - pip install hatch + - hatch run lint + test: + image: python:3.11 + commands: + - pip install hatch + - hatch run test + publish-package: + image: python:3.11 + commands: + - pip install hatch + - hatch build + - hatch publish --repo $PIP_REPOSITORY --user $PIP_USERNAME --auth $PIP_TOKEN --no-prompt + secrets: + - pip_repository + - pip_username + - pip_token + when: + event: tag + nightly-image: + image: docker + commands: + - "docker login git.libertytechforce.com -u $DOCKER_USERNAME -p $DOCKER_TOKEN" + - "docker build -t git.libertytechforce.com/raoul/http2smtp:nightly -t git.libertytechforce.com/raoul/http2smtp:${CI_COMMIT_SHA:0:8} -f Dockerfile.nightly ." + - "docker push git.libertytechforce.com/raoul/http2smtp:nightly" + - "docker push git.libertytechforce.com/raoul/http2smtp:${CI_COMMIT_SHA:0:8}" + volumes: + - /var/run/docker.sock:/var/run/docker.sock + secrets: + - docker_username + - docker_token + when: + - branch: master + event: push + release-image: + image: docker + commands: + - "docker login git.libertytechforce.com -u $DOCKER_USERNAME -p $DOCKER_TOKEN" + - "docker build -t git.libertytechforce.com/raoul/http2smtp:latest -t git.libertytechforce.com/raoul/http2smtp:${CI_COMMIT_TAG##v} -f Dockerfile.release ." + - "docker push git.libertytechforce.com/raoul/http2smtp:latest" + - "docker push git.libertytechforce.com/raoul/http2smtp:${CI_COMMIT_TAG##v}" + volumes: + - /var/run/docker.sock:/var/run/docker.sock + secrets: + - docker_username + - docker_token + when: + - branch: master + event: tag diff --git a/Dockerfile.nightly b/Dockerfile.nightly new file mode 100644 index 0000000..0a6d421 --- /dev/null +++ b/Dockerfile.nightly @@ -0,0 +1,10 @@ +FROM python:3.11-alpine + +WORKDIR /app +ADD . /app +RUN apk add git +RUN pip install -e . +RUN pip install uvicorn[standard] + +EXPOSE 8000 +CMD ["uvicorn", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "http2smtp.app:app"] diff --git a/Dockerfile.release b/Dockerfile.release new file mode 100644 index 0000000..890ef69 --- /dev/null +++ b/Dockerfile.release @@ -0,0 +1,6 @@ +FROM python:3.11-alpine + +RUN pip install --extra-index-url https://git.libertytechforce.com/api/packages/raoul/pypi/simple/ http2smtp uvicorn[standard] + +EXPOSE 8000 +CMD ["uvicorn", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "http2smtp.app:app"] diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..779e827 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023-present Raoul Snyman + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..540b7d6 --- /dev/null +++ b/README.rst @@ -0,0 +1,20 @@ +========= +http2smtp +========= + +**Table of Contents** + +- `Installation <#installation>`_ +- `License <#license>`_ + +Installation +------------ + +.. code-block:: sh + + pip install http2smtp + +License +------- + +``http2smtp`` is distributed under the terms of the `MIT `_ license. diff --git a/http2smtp/__about__.py b/http2smtp/__about__.py new file mode 100644 index 0000000..478f871 --- /dev/null +++ b/http2smtp/__about__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: 2023-present Raoul Snyman +# +# SPDX-License-Identifier: MIT +__version__ = '0.0.1' diff --git a/http2smtp/__init__.py b/http2smtp/__init__.py new file mode 100644 index 0000000..5b1c1b8 --- /dev/null +++ b/http2smtp/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2023-present Raoul Snyman +# +# SPDX-License-Identifier: MIT diff --git a/http2smtp/app.py b/http2smtp/app.py new file mode 100644 index 0000000..ce243e9 --- /dev/null +++ b/http2smtp/app.py @@ -0,0 +1,26 @@ +from fastapi import FastAPI +from fastapi.responses import JSONResponse, RedirectResponse + +from http2smtp.models import Email +from http2smtp.message import BodyRequiredError, build_message +from http2smtp.smtp import send_email + +app = FastAPI() + + +@app.get('/') +async def index() -> RedirectResponse: + return RedirectResponse(url='/docs') + + +@app.post('/smtp') +async def smtp_send(email: Email): + try: + message = build_message(email) + except BodyRequiredError as e: + return JSONResponse(status=400, content={'error': str(e)}) + try: + send_email(email.from_email, email.password, message) + except Exception as e: + return JSONResponse(status=400, content={'error': str(e)}) + return {"status": "success"} diff --git a/http2smtp/message.py b/http2smtp/message.py new file mode 100644 index 0000000..86e96db --- /dev/null +++ b/http2smtp/message.py @@ -0,0 +1,38 @@ +from bs4 import BeautifulSoup +from fastapi_mail import MessageSchema, MessageType +from http2smtp.models import Email + + +class BodyRequiredError(Exception): + def __init__(self): + super().__init__('Either "html_body" or "text_body" are required, but neither were supplied') + + +def _strip_html(html: str) -> str: + """Strip HTML tags from the text and return just the plain text""" + soup = BeautifulSoup(html, 'html.parser') + return soup.get_text() + + +def build_message(email: Email) -> MessageSchema: + """Build an EmailMessage from an Email""" + recipients: list[str] = [email.to_email] if isinstance(email.to_email, str) else email.to_email + msg = MessageSchema( + subject=email.subject, + recipients=recipients, + subtype=MessageType.html + ) + if not email.html_body and not email.text_body: + raise BodyRequiredError() + if email.html_body and not email.text_body: + email.text_body = _strip_html(email.html_body) + + if email.html_body: + msg.subtype = MessageType.html + msg.body = email.html_body + msg.alternative_body = email.text_body + else: + msg.subtype = MessageType.plain + msg.body = email.text_body + + return msg diff --git a/http2smtp/models.py b/http2smtp/models.py new file mode 100644 index 0000000..9c7b1e3 --- /dev/null +++ b/http2smtp/models.py @@ -0,0 +1,10 @@ +from pydantic import BaseModel + + +class Email(BaseModel): + from_email: str + password: str + to_email: str | list[str] + subject: str + html_body: str | None = None + text_body: str | None = None diff --git a/http2smtp/settings.py b/http2smtp/settings.py new file mode 100644 index 0000000..06315ea --- /dev/null +++ b/http2smtp/settings.py @@ -0,0 +1,19 @@ +from pydantic_settings import BaseSettings, SettingsConfigDict +from fastapi_mail import ConnectionConfig as BaseConfig + + +class Settings(BaseSettings): + host: str = 'localhost' + port: int = 8025 + sslmode: str = 'none' + + model_config = SettingsConfigDict(env_file='.env') + + +class MailConfig(BaseConfig): + model_config = SettingsConfigDict(env_file='.env') + + +settings = Settings() +mail_config = MailConfig(MAIL_USERNAME='', MAIL_PASSWORD='', MAIL_FROM='default@example.com', MAIL_PORT=25, + MAIL_SERVER='', MAIL_STARTTLS=False, MAIL_SSL_TLS=False) diff --git a/http2smtp/smtp.py b/http2smtp/smtp.py new file mode 100644 index 0000000..7544128 --- /dev/null +++ b/http2smtp/smtp.py @@ -0,0 +1,12 @@ +from fastapi_mail import FastMail, MessageSchema +from http2smtp.settings import mail_config + + +def send_email(from_address: str, password: str, message: MessageSchema) -> None: + """Send the e-mail""" + mail_config.MAIL_USERNAME = from_address + mail_config.MAIL_PASSWORD = password + mail_config.MAIL_FROM = from_address + + fm = FastMail(mail_config) + fm.send_message(message) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a406d7e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,66 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "http2smtp" +description = 'An HTTP to SMTP gateway' +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +keywords = [] +authors = [ + { name = "Raoul Snyman", email = "raoul@snyman.info" }, +] +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = [ + "bs4", + "FastAPI", + "fastapi-mail", + "pydantic-settings", + "uvicorn[standard]" +] +dynamic = ["version"] + +[project.urls] +Documentation = "https://git.libertytechforce.com/libertytechforce/http2smtp#readme" +Issues = "https://git.libertytechforce.com/libertytechforce/http2smtp/issues" +Source = "https://git.libertytechforce.com/libertytechforce/http2smtp" + +[tool.hatch.version] +source = "vcs" + +[tool.hatch.envs.default] +dependencies = [ + "flake8", + "pytest", + "pytest-cov" +] + +[tool.hatch.envs.default.scripts] +serve = "uvicorn http2smtp.app:app --reload" +lint = "flake8" +test = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=http2smtp --cov=tests {args}" + +[[tool.hatch.envs.test.matrix]] +python = ["311"] + +[tool.coverage.run] +branch = true +parallel = true +omit = [ + "http2smtp/__about__.py", +] + +[tool.coverage.report] +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..5b1c1b8 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2023-present Raoul Snyman +# +# SPDX-License-Identifier: MIT diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_message.py b/tests/test_message.py new file mode 100644 index 0000000..8da38b0 --- /dev/null +++ b/tests/test_message.py @@ -0,0 +1,30 @@ +from http2smtp.models import Email +from http2smtp.message import build_message + + +def test_build_message_html(): + """Test building a message with an HTML body""" + subject = 'This is a test e-mail' + html_body = '

This is the body of the html e-mail.

' + email = Email(from_email='test@example.com', to_email='another@example.com', subject=subject, + html_body=html_body, password='dfsghasdf') + + message = build_message(email) + + assert message.subject == subject + assert message.body == html_body + assert message.alternative_body == 'This is the body of the html e-mail.' + + +def test_build_message_text(): + """Test building a message with a plain text body""" + subject = 'This is a test e-mail' + text_body = 'This is the body of the text e-mail.' + email = Email(from_email='test@example.com', to_email='another@example.com', subject=subject, + text_body=text_body, password='fghfhergsdf') + + message = build_message(email) + + assert message.subject == subject + assert message.body == text_body + assert message.alternative_body is None diff --git a/tests/test_smtp.py b/tests/test_smtp.py new file mode 100644 index 0000000..6167dd0 --- /dev/null +++ b/tests/test_smtp.py @@ -0,0 +1,24 @@ +import secrets + +from fastapi_mail import MessageSchema, MessageType + +from http2smtp.smtp import send_email + + +def test_send_email(): + """Test that we can send e-mail without SSL/TLS""" + # GIVEN: A valid login to the server + from_address = 'test@example.com' + password = secrets.token_urlsafe(8) + + message = MessageSchema( + subject='Test e-mail', + recipients=['another@example.com'], + body='This is the body', + subtype=MessageType.plain + ) + + # WHEN: An e-mail is sent + send_email(from_address, password, message) + + # THEN: The message should have been sent