commit 8204e054c0654b889eeb4488187f12b645260917
parent 490b840e0ffd284cc3bfb604063e978db9b02bec
Author: William Lindholm <william_lindholm@outlook.com>
Date: Tue, 31 Oct 2023 22:28:02 +0100
Now saving incoming messages in sqlite db.
Diffstat:
4 files changed, 109 insertions(+), 22 deletions(-)
diff --git a/.idea/PortfolioBridge.iml b/.idea/PortfolioBridge.iml
@@ -4,7 +4,7 @@
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
- <orderEntry type="inheritedJdk" />
+ <orderEntry type="jdk" jdkName="Python 3.11 (PortfolioBridge)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
diff --git a/WebAPI/__init__.py b/WebAPI/__init__.py
@@ -1,17 +1,22 @@
from flask import Flask
from flask_restx import Resource, Api, fields
-from WebAPI.mailer import *
+from WebAPI.mailer import Mailer
+from WebAPI.dbrepository import DatabaseRepository
app = Flask(__name__)
api = Api(app)
+mailer = Mailer()
+db_repo = DatabaseRepository()
+
contact_fields = api.model('Contact', {
'email': fields.String(required=True),
'name': fields.String(required=True),
'message_content': fields.String(required=True)
})
+
@api.route('/contact')
class contact(Resource):
@api.expect(contact_fields)
@@ -21,10 +26,36 @@ class contact(Resource):
name = data['name']
message_content = data['message_content']
- formatted_subject = format_subject(email)
- formatted_message = format_message(name, email, message_content)
+ formatted_subject = mailer.format_subject(email)
+ formatted_message = mailer.format_message(name, email, message_content)
+
+ try:
+ mailer.send_notification(formatted_subject, formatted_message)
+ except Exception as e:
+ return {"message": f"An unknown error occurred: {str(e)}"}, 500
+
+ db_repo.save_message(name, email, formatted_subject, message_content) # Save message to database
+
+ return {"message": "Message sent and saved successfully"}, 200
+
+
+@api.route('/messages')
+class Messages(Resource):
+ def get(self):
+ messages = db_repo.fetch_messages()
+ formatted_messages = [
+ {
+ "id": message[0],
+ "name": message[1],
+ "email": message[2],
+ "subject": message[3],
+ "message_content": message[4],
+ "timestamp": message[5]
+ }
+ for message in messages
+ ]
+ return formatted_messages, 200
- send_email(formatted_subject, formatted_message)
if __name__ == '__main__':
app.run(debug=True)
\ No newline at end of file
diff --git a/WebAPI/dbrepository.py b/WebAPI/dbrepository.py
@@ -0,0 +1,45 @@
+import sqlite3
+
+class DatabaseRepository:
+ DATABASE_FILE = 'messages.db'
+
+ def __init__(self):
+ self.initialize_db()
+
+ def initialize_db(self):
+ conn = sqlite3.connect(self.DATABASE_FILE)
+ cursor = conn.cursor()
+ cursor.execute(
+ """
+ CREATE TABLE IF NOT EXISTS messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ message_content TEXT NOT NULL,
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
+ );
+ """
+ )
+ conn.commit()
+ conn.close()
+
+ def save_message(self, name, email, subject, message_content):
+ conn = sqlite3.connect(self.DATABASE_FILE)
+ cursor = conn.cursor()
+ cursor.execute(
+ """
+ INSERT INTO messages (name, email, subject, message_content)
+ VALUES (?, ?, ?, ?)
+ """, (name, email, subject, message_content)
+ )
+ conn.commit()
+ conn.close()
+
+ def fetch_messages(self):
+ conn = sqlite3.connect(self.DATABASE_FILE)
+ cursor = conn.cursor()
+ cursor.execute("SELECT * FROM messages ORDER BY timestamp DESC")
+ messages = cursor.fetchall()
+ conn.close()
+ return messages
+\ No newline at end of file
diff --git a/WebAPI/mailer.py b/WebAPI/mailer.py
@@ -1,25 +1,35 @@
import smtplib
import json
+class Mailer:
+ def __init__(self):
+ with open('settings.json', 'r') as f:
+ settings = json.load(f)
-def send_email(subject, message):
- with open('secrets.json', 'r') as f:
- credentials = json.load(f)
- with open('settings.json', 'r') as f:
- settings = json.load(f)
+ self.notification_recipient = settings['recipient_email']
+ self.email = settings['email']
+ self.password = settings['email_password']
+ self.smtpsrv = settings['smtp_server']
- from_email = credentials['email']
- password = credentials['password']
- to_email = settings['recipient_email']
+ def send(self, subject, message, recipient):
+ with smtplib.SMTP(self.smtpsrv, 587) as server:
+ server.starttls()
+ server.login(self.email, self.password)
+ server.sendmail(self.email, recipient, f"Subject: {subject}\n\n{message}")
- with smtplib.SMTP(credentials['smtp_server'], 587) as server:
- server.starttls()
- server.login(from_email, password)
- server.sendmail(from_email, to_email, f"Subject: {subject}\n\n{message}")
+ def send_notification(self, subject, message):
+ with open('settings.json', 'r') as f:
+ settings = json.load(f)
+ recipient = settings['recipient_email']
+ self.send(subject, message, recipient)
+ def send_confirmation(self, recipient):
+ with open('confirmation.html', 'r', encoding='utf-8') as file:
+ html_content = file.read()
+ self.send('Confirmation Email', html_content, recipient)
-def format_message(name, email, content):
- return f"MESSAGE RECEIVED FROM: {name}\nWITH EMAIL: {email}\nCONTENT:\n{content}"
+ def format_message(self, name, email, content):
+ return f"MESSAGE RECEIVED FROM: {name}\nWITH EMAIL: {email}\nCONTENT:\n{content}"
-def format_subject(email):
- return f"Contact from: {email}"
-\ No newline at end of file
+ def format_subject(self, email):
+ return f"Contact from: {email}"
+\ No newline at end of file