amazonpricetracker / smtp_server.py
shoaibrza9999's picture
Upload folder using huggingface_hub
8aa040a verified
Raw
History Blame Contribute Delete
1.91 kB
from flask import Flask, request, jsonify
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
API_KEY = os.environ.get('API_KEY', '') # Optional, but recommended to prevent abuse
@app.route('/send-email', methods=['POST'])
def send_email():
if API_KEY:
provided_key = request.headers.get('x-api-key')
if provided_key != API_KEY:
return jsonify({'error': 'Unauthorized'}), 401
data = request.json
if not data:
return jsonify({'error': 'Missing JSON payload'}), 400
to_email = data.get('to_email')
subject = data.get('subject')
body = data.get('body')
smtp_server = data.get('smtp_server')
smtp_port = data.get('smtp_port')
smtp_user = data.get('smtp_user')
smtp_password = data.get('smtp_password')
if not all([to_email, subject, body]):
return jsonify({'error': 'Missing to_email, subject, or body'}), 400
if not all([smtp_server, smtp_port, smtp_user, smtp_password]):
return jsonify({'error': 'Missing SMTP credentials in payload'}), 400
msg = MIMEMultipart()
msg['From'] = smtp_user
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain', 'utf-8'))
try:
server = smtplib.SMTP(smtp_server, int(smtp_port), timeout=10)
server.starttls()
server.login(smtp_user, smtp_password)
server.send_message(msg)
server.quit()
return jsonify({'message': f'Email successfully sent to {to_email}'}), 200
except Exception as e:
print(f"Error sending email: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'ok'}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)