nonzeroexit commited on
Commit
166a494
·
verified ·
1 Parent(s): f11cb0a

Rename email_service/temp to email_service/email_sender_api.py

Browse files
email_service/email_sender_api.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from flask_cors import CORS
3
+ import smtplib
4
+ from email.mime.multipart import MIMEMultipart
5
+ from email.mime.text import MIMEText
6
+ from email.mime.base import MIMEBase
7
+ from email import encoders
8
+ import base64
9
+ import os
10
+
11
+ app = Flask(__name__)
12
+ CORS(app) # Allows requests from your frontend
13
+
14
+ # Environment variables for SMTP configuration (MUST BE SET before running)
15
+ SMTP_SERVER_HOST = os.environ.get("SMTP_SERVER_HOST")
16
+ SMTP_SERVER_PORT = os.environ.get("SMTP_SERVER_PORT")
17
+ SMTP_SENDER_EMAIL = os.environ.get("SMTP_SENDER_EMAIL")
18
+ SMTP_SENDER_PASSWORD = os.environ.get("SMTP_SENDER_PASSWORD")
19
+
20
+ @app.route('/send-report-via-email', methods=['POST']) # Changed endpoint name for clarity
21
+ def handle_send_email():
22
+ print("EMAIL_SENDER_API: Received request at /send-report-via-email") # Log request
23
+ if not all([SMTP_SERVER_HOST, SMTP_SERVER_PORT, SMTP_SENDER_EMAIL, SMTP_SENDER_PASSWORD]):
24
+ error_msg = "EMAIL_SENDER_API: ERROR - SMTP environment variables not fully set."
25
+ print(error_msg)
26
+ return jsonify({"status": "error", "message": "Email server configuration incomplete on the API."}), 500
27
+
28
+ try:
29
+ SMTP_PORT_INT = int(SMTP_SERVER_PORT)
30
+ except ValueError:
31
+ error_msg = "EMAIL_SENDER_API: ERROR - Invalid SMTP_SERVER_PORT configured."
32
+ print(error_msg)
33
+ return jsonify({"status": "error", "message": "Invalid email server port configured on the API."}), 500
34
+
35
+ data = request.json
36
+ if not data:
37
+ print("EMAIL_SENDER_API: No JSON data received.")
38
+ return jsonify({"status": "error", "message": "No data received by email API."}), 400
39
+
40
+ recipient_email = data.get('recipient_email')
41
+ pdf_base64_data = data.get('pdf_base64_data')
42
+ pdf_filename = data.get('pdf_filename')
43
+ print(f"EMAIL_SENDER_API: Attempting to send to: {recipient_email}, Filename: {pdf_filename}")
44
+
45
+
46
+ if not all([recipient_email, pdf_base64_data, pdf_filename]):
47
+ print("EMAIL_SENDER_API: Missing required data in JSON payload.")
48
+ return jsonify({"status": "error", "message": "Missing required data: recipient_email, pdf_base64_data, or pdf_filename."}), 400
49
+
50
+ try:
51
+ msg = MIMEMultipart()
52
+ msg['From'] = SMTP_SENDER_EMAIL
53
+ msg['To'] = recipient_email
54
+ msg['Subject'] = f"EPIC-AMP Analysis Report: {pdf_filename}" # Updated subject
55
+ body = f"""Dear User,\n\nPlease find your EPIC-AMP analysis report attached.\n\nFilename: {pdf_filename}\n\nThis report includes details on your sequence analysis.\n\nThank you for using EPIC-AMP!\n\nBest regards,\nThe EPIC-AMP Team\nBioinformatics and Computational Biology Unit, Zewail City\nFor inquiries: [email protected]"""
56
+ msg.attach(MIMEText(body, 'plain'))
57
+
58
+ pdf_data_bytes = base64.b64decode(pdf_base64_data)
59
+ part = MIMEBase('application', 'octet-stream')
60
+ part.set_payload(pdf_data_bytes)
61
+ encoders.encode_base64(part)
62
+ part.add_header('Content-Disposition', f"attachment; filename=\"{pdf_filename}\"")
63
+ msg.attach(part)
64
+
65
+ print(f"EMAIL_SENDER_API: Connecting to SMTP server {SMTP_SERVER_HOST}:{SMTP_PORT_INT}")
66
+ with smtplib.SMTP(SMTP_SERVER_HOST, SMTP_PORT_INT) as server:
67
+ server.set_debuglevel(1) # More verbose SMTP logs
68
+ server.ehlo()
69
+ if SMTP_PORT_INT == 587: # TLS
70
+ print("EMAIL_SENDER_API: Starting TLS...")
71
+ server.starttls()
72
+ server.ehlo()
73
+ print("EMAIL_SENDER_API: Logging in...")
74
+ server.login(SMTP_SENDER_EMAIL, SMTP_SENDER_PASSWORD)
75
+ print("EMAIL_SENDER_API: Sending mail...")
76
+ server.sendmail(SMTP_SENDER_EMAIL, recipient_email, msg.as_string())
77
+ print("EMAIL_SENDER_API: Mail sent.")
78
+
79
+ success_msg = f"Report successfully sent to {recipient_email}."
80
+ print(f"EMAIL_SENDER_API: {success_msg}")
81
+ return jsonify({"status": "success", "message": success_msg}), 200
82
+
83
+ except smtplib.SMTPAuthenticationError as e:
84
+ error_msg = f"EMAIL_SENDER_API: SMTP Authentication Error - {e}"
85
+ print(error_msg)
86
+ return jsonify({"status": "error", "message": "Email server authentication failed on the API."}), 500
87
+ except Exception as e:
88
+ import traceback
89
+ error_msg = f"EMAIL_SENDER_API: Error sending email to {recipient_email} - {e}"
90
+ print(error_msg)
91
+ print(traceback.format_exc())
92
+ return jsonify({"status": "error", "message": f"Failed to send email via API: {e}"}), 500
93
+
94
+ if __name__ == '__main__':
95
+ # IMPORTANT: Run this on a DIFFERENT port than your main Gradio app (usually 7860)
96
+ api_port = 5002 # Using port 5002 here for the email API
97
+ print(f"Starting Email Sender API Service on port {api_port}...")
98
+ print(f"SMTP Config Loaded: Server={SMTP_SERVER_HOST}, Port={SMTP_SERVER_PORT}, User Email Set={SMTP_SENDER_EMAIL is not None}")
99
+ if not all([SMTP_SERVER_HOST, SMTP_SERVER_PORT, SMTP_SENDER_EMAIL, SMTP_SENDER_PASSWORD]):
100
+ print("WARNING: EMAIL_SENDER_API - SMTP environment variables are not fully set. Email sending will likely fail.")
101
+ app.run(host='0.0.0.0', port=api_port, debug=True) # debug=True for development feedback
email_service/temp DELETED
File without changes