summaryrefslogtreecommitdiff
path: root/contact.py
blob: 568f114b6c2146719d63593d8f2a70bed57f5557 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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)