From 2eae36e8fd37b515bdc1f7810fe731f1bf310020 Mon Sep 17 00:00:00 2001 From: Thastertyn Date: Sun, 10 Mar 2024 21:41:48 +0100 Subject: [PATCH] Initial work on mail sending --- app/__init__.py | 2 ++ app/config.py | 8 +++++++- app/mail_utils.py | 15 +++++++++++++++ app/services/user_service.py | 7 +++++++ 4 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 app/mail_utils.py diff --git a/app/__init__.py b/app/__init__.py index 6635132..1478e2c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,10 @@ from flask import Flask from flask_jwt_extended import JWTManager +from flask_mail import Mail app = Flask(__name__) jwt_manager = JWTManager(app) +mail = Mail(app) def create_app(): from app.api import bp, bp_errors, bp_product, bp_user, bp_cart diff --git a/app/config.py b/app/config.py index 438cda7..12bc616 100644 --- a/app/config.py +++ b/app/config.py @@ -19,4 +19,10 @@ class FlaskProduction: class FlaskTesting: DEBUG = True JWT_SECRET_KEY = os.environ.get('JWT_SECRET_KEY') - SERVER_NAME = os.environ.get('HOST') + ':' + os.environ.get('PORT') \ No newline at end of file + SERVER_NAME = os.environ.get('HOST') + ':' + os.environ.get('PORT') + + MAIL_SERVER = os.environ.get('MAIL_SERVER') + MAIL_PORT = os.environ.get('MAIL_USERNAME') + MAIL_USERNAME = os.environ.get('MAIL_USERNAME') + MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') + MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') \ No newline at end of file diff --git a/app/mail_utils.py b/app/mail_utils.py new file mode 100644 index 0000000..768ea98 --- /dev/null +++ b/app/mail_utils.py @@ -0,0 +1,15 @@ +from flask_mail import Message + +from app import mail + + +def send_mail(subject: str, recipient: str, body: str): + msg = Message(subject, recipients=[recipient]) + msg.body = body + + try: + mail.send(msg) + return True + except Exception as e: + print(f"Failed to send email. Error: {e}") + return False \ No newline at end of file diff --git a/app/services/user_service.py b/app/services/user_service.py index 56f91a8..0e06184 100644 --- a/app/services/user_service.py +++ b/app/services/user_service.py @@ -9,6 +9,8 @@ from flask_jwt_extended import create_access_token from app.extensions import db_cursor, db_connection from app.extensions import jwt_redis_blocklist +from app.mail_utils import send_mail + class UserService: """ @@ -59,6 +61,11 @@ class UserService: print(f"Error: {e}") return {"Failed": "Failed to insert into database. Username or email are likely in use already"}, 500 + # TODO Implement mail sending + # Currently throws error - connection refused + + # send_mail("Successfully registered!", email, "Congratulations! Your account has been successfully created.\nThis mail also serves as a test that the email address is correct") + return {"Success": "User created successfully"}, 200 @staticmethod