diff options
Diffstat (limited to 'contact.py')
| -rwxr-xr-x | contact.py | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/contact.py b/contact.py new file mode 100755 index 0000000..568f114 --- /dev/null +++ b/contact.py @@ -0,0 +1,61 @@ +from flask import Flask, request, jsonify +from flask_cors import CORS +import smtplib +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +import logging + +app = Flask(__name__) +CORS(app, origins=["https://portfolio.tylerhoang.xyz"]) + +MAIL_HOST = "mail.tylerhoang.xyz" +MAIL_PORT = 25 +FROM_ADDR = "noreply@tylerhoang.xyz" +TO_ADDR = "tyler@tylerhoang.xyz" + +logging.basicConfig(level=logging.INFO) + +@app.route("/contact", methods=["POST"]) +def contact(): + data = request.get_json(silent=True) or request.form + + name = (data.get("name") or "").strip() + email = (data.get("email") or "").strip() + message = (data.get("message") or "").strip() + + if not name or not email or not message: + return jsonify({"error": "All fields are required."}), 400 + + if "@" not in email or "." not in email: + return jsonify({"error": "Invalid email address."}), 400 + + if len(message) > 5000: + return jsonify({"error": "Message too long."}), 400 + + try: + msg = MIMEMultipart("alternative") + msg["Subject"] = f"Portfolio contact from {name}" + msg["From"] = FROM_ADDR + msg["To"] = TO_ADDR + msg["Reply-To"] = email + + body = f"""Name: {name} +Email: {email} + +{message} +""" + msg.attach(MIMEText(body, "plain")) + + with smtplib.SMTP(MAIL_HOST, MAIL_PORT, timeout=10) as smtp: + smtp.sendmail(FROM_ADDR, TO_ADDR, msg.as_string()) + + app.logger.info(f"Contact form submitted by {name} <{email}>") + return jsonify({"success": True}), 200 + + except Exception as e: + app.logger.error(f"Mail error: {e}") + return jsonify({"error": "Failed to send message. Please try again later."}), 500 + + +if __name__ == "__main__": + app.run(host="127.0.0.1", port=5001) |
