nonzeroexit commited on
Commit
0ff7b30
·
verified ·
1 Parent(s): 3959ff2

Update email_sender_api.py

Browse files
Files changed (1) hide show
  1. email_sender_api.py +42 -17
email_sender_api.py CHANGED
@@ -1,15 +1,35 @@
1
- # ... (keep existing imports and Flask app setup, SMTP config variables) ...
 
 
 
 
 
 
 
 
 
 
2
 
3
- SMTP_CONNECTION_TIMEOUT = 30 # Increased slightly for good measure
4
- SMTP_COMMAND_TIMEOUT = 30 # Increased slightly for good measure
 
 
5
 
6
- @app.route('/send-report-via-email', methods=['POST']) # Keep the same endpoint
 
 
 
 
 
 
 
 
 
7
  def handle_send_email():
8
  request_id = base64.b64encode(os.urandom(6)).decode('utf-8')
9
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Received request at /send-report-via-email")
10
 
11
  if not all([SMTP_SERVER_HOST, SMTP_SERVER_PORT, SMTP_SENDER_EMAIL, SMTP_SENDER_PASSWORD]):
12
- # ... (same error handling for missing SMTP config as before) ...
13
  error_msg = "EMAIL_SENDER_API (HF) [{request_id}]: ERROR - SMTP environment variables (Secrets) not fully set."
14
  print(error_msg)
15
  return jsonify({"status": "error", "message": "Email server configuration incomplete on the API."}), 500
@@ -17,29 +37,28 @@ def handle_send_email():
17
  try:
18
  SMTP_PORT_INT = int(SMTP_SERVER_PORT)
19
  except ValueError:
20
- # ... (same error handling for invalid port) ...
21
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: ERROR - Invalid SMTP_SERVER_PORT: '{SMTP_SERVER_PORT}'."
22
  print(error_msg)
23
  return jsonify({"status": "error", "message": "Invalid email server port configured on the API."}), 500
24
 
25
  data = request.json
26
  if not data:
27
- # ... (same error handling for no data) ...
28
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - No JSON data received.")
29
  return jsonify({"status": "error", "message": "No data received by email API."}), 400
30
 
31
  recipient_email = data.get('recipient_email')
32
- # We are not using pdf_base64_data or pdf_filename in this simplified test
 
33
 
34
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Attempting to send to: {recipient_email}")
35
 
36
- if not recipient_email: # Only recipient email is strictly needed for this test
37
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Missing recipient_email in JSON payload.")
38
  return jsonify({"status": "error", "message": "Missing required data: recipient_email."}), 400
39
 
40
  try:
41
  # Create a simple plain text message
42
- simple_msg = MIMEMultipart() # Still use MIMEMultipart for proper headers
43
  simple_msg['From'] = SMTP_SENDER_EMAIL
44
  simple_msg['To'] = recipient_email
45
  simple_msg['Subject'] = "EPIC-AMP - Simple Connectivity Test"
@@ -86,12 +105,12 @@ def handle_send_email():
86
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: {success_msg}")
87
  return jsonify({"status": "success", "message": success_msg}), 200
88
 
89
- # Keep all the specific exception handling blocks as they were
90
  except smtplib.SMTPConnectError as e:
91
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - SMTP Connect Error. {e}"
92
  print(error_msg); traceback.print_exc()
93
  return jsonify({"status": "error", "message": f"SIMPLIFIED TEST - Could not connect: {e.strerror if hasattr(e, 'strerror') else e}"}), 503
94
- except smtplib.SMTPHeloError as e: # Keep other specific exceptions
95
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - SMTP Helo/Ehlo Error. {e}"
96
  print(error_msg); traceback.print_exc()
97
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Server HELO/EHLO error."}), 502
@@ -99,7 +118,6 @@ def handle_send_email():
99
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - SMTP Authentication Error. {e}"
100
  print(error_msg); traceback.print_exc()
101
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Email server authentication failed."}), 500
102
- # ... include ALL other smtplib exceptions and socket exceptions from the previous version of email_sender_api.py ...
103
  except socket.timeout as e:
104
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Socket Timeout. {e}"
105
  print(error_msg); traceback.print_exc()
@@ -108,8 +126,8 @@ def handle_send_email():
108
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Address-related error. {e}"
109
  print(error_msg); traceback.print_exc()
110
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Could not resolve hostname."}), 503
111
- except OSError as e: # Specifically catch OSError for "Network is unreachable"
112
- if e.errno == 101: # Network is unreachable
113
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - OSError [Errno 101] Network is unreachable. {e}"
114
  print(error_msg); traceback.print_exc()
115
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Network is unreachable from API server."}), 503
@@ -123,6 +141,13 @@ def handle_send_email():
123
  traceback.print_exc()
124
  return jsonify({"status": "error", "message": f"SIMPLIFIED TEST - Unexpected API error: {type(e).__name__}"}), 500
125
 
126
- # The if __name__ == '__main__': block for local testing can remain commented out or as is
 
 
 
127
  # if __name__ == '__main__':
128
- # # ... local testing startup ...
 
 
 
 
 
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 # Not used in simplified version
7
+ # from email import encoders # Not used in simplified version
8
+ import base64
9
+ import os
10
+ import socket
11
+ import traceback
12
 
13
+ # <<<--- FLASK APP INITIALIZATION MUST BE HERE (TOP LEVEL) --->>>
14
+ app = Flask(__name__)
15
+ CORS(app)
16
+ # <<<--------------------------------------------------------->>>
17
 
18
+ # Environment variables will be set as Secrets in Hugging Face Space settings
19
+ SMTP_SERVER_HOST = os.environ.get("SMTP_SERVER_HOST")
20
+ SMTP_SERVER_PORT = os.environ.get("SMTP_SERVER_PORT")
21
+ SMTP_SENDER_EMAIL = os.environ.get("SMTP_SENDER_EMAIL")
22
+ SMTP_SENDER_PASSWORD = os.environ.get("SMTP_SENDER_PASSWORD")
23
+
24
+ SMTP_CONNECTION_TIMEOUT = 30
25
+ SMTP_COMMAND_TIMEOUT = 30
26
+
27
+ @app.route('/send-report-via-email', methods=['POST']) # This decorator now correctly sees 'app'
28
  def handle_send_email():
29
  request_id = base64.b64encode(os.urandom(6)).decode('utf-8')
30
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Received request at /send-report-via-email")
31
 
32
  if not all([SMTP_SERVER_HOST, SMTP_SERVER_PORT, SMTP_SENDER_EMAIL, SMTP_SENDER_PASSWORD]):
 
33
  error_msg = "EMAIL_SENDER_API (HF) [{request_id}]: ERROR - SMTP environment variables (Secrets) not fully set."
34
  print(error_msg)
35
  return jsonify({"status": "error", "message": "Email server configuration incomplete on the API."}), 500
 
37
  try:
38
  SMTP_PORT_INT = int(SMTP_SERVER_PORT)
39
  except ValueError:
 
40
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: ERROR - Invalid SMTP_SERVER_PORT: '{SMTP_SERVER_PORT}'."
41
  print(error_msg)
42
  return jsonify({"status": "error", "message": "Invalid email server port configured on the API."}), 500
43
 
44
  data = request.json
45
  if not data:
 
46
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - No JSON data received.")
47
  return jsonify({"status": "error", "message": "No data received by email API."}), 400
48
 
49
  recipient_email = data.get('recipient_email')
50
+ # pdf_base64_data = data.get('pdf_base64_data') # Not using these in simplified test
51
+ # pdf_filename = data.get('pdf_filename') # Not using these in simplified test
52
 
53
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Attempting to send to: {recipient_email}")
54
 
55
+ if not recipient_email:
56
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Missing recipient_email in JSON payload.")
57
  return jsonify({"status": "error", "message": "Missing required data: recipient_email."}), 400
58
 
59
  try:
60
  # Create a simple plain text message
61
+ simple_msg = MIMEMultipart()
62
  simple_msg['From'] = SMTP_SENDER_EMAIL
63
  simple_msg['To'] = recipient_email
64
  simple_msg['Subject'] = "EPIC-AMP - Simple Connectivity Test"
 
105
  print(f"EMAIL_SENDER_API (HF) [{request_id}]: {success_msg}")
106
  return jsonify({"status": "success", "message": success_msg}), 200
107
 
108
+ # Keep all the specific exception handling blocks
109
  except smtplib.SMTPConnectError as e:
110
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - SMTP Connect Error. {e}"
111
  print(error_msg); traceback.print_exc()
112
  return jsonify({"status": "error", "message": f"SIMPLIFIED TEST - Could not connect: {e.strerror if hasattr(e, 'strerror') else e}"}), 503
113
+ except smtplib.SMTPHeloError as e:
114
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - SMTP Helo/Ehlo Error. {e}"
115
  print(error_msg); traceback.print_exc()
116
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Server HELO/EHLO error."}), 502
 
118
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - SMTP Authentication Error. {e}"
119
  print(error_msg); traceback.print_exc()
120
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Email server authentication failed."}), 500
 
121
  except socket.timeout as e:
122
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Socket Timeout. {e}"
123
  print(error_msg); traceback.print_exc()
 
126
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - Address-related error. {e}"
127
  print(error_msg); traceback.print_exc()
128
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Could not resolve hostname."}), 503
129
+ except OSError as e:
130
+ if e.errno == 101:
131
  error_msg = f"EMAIL_SENDER_API (HF) [{request_id}]: SIMPLIFIED TEST - OSError [Errno 101] Network is unreachable. {e}"
132
  print(error_msg); traceback.print_exc()
133
  return jsonify({"status": "error", "message": "SIMPLIFIED TEST - Network is unreachable from API server."}), 503
 
141
  traceback.print_exc()
142
  return jsonify({"status": "error", "message": f"SIMPLIFIED TEST - Unexpected API error: {type(e).__name__}"}), 500
143
 
144
+ # The if __name__ == '__main__': block for local testing:
145
+ # On Hugging Face Spaces with Gunicorn, Gunicorn directly imports and runs the 'app' object,
146
+ # so this block isn't strictly executed by Gunicorn.
147
+ # It's useful if you want to run this script directly with `python email_sender_api.py` for local testing.
148
  # if __name__ == '__main__':
149
+ # # For local testing, set your ENV VARS in this terminal session before running
150
+ # api_port = int(os.environ.get("PORT", 5002)) # Default to 5002 for local test
151
+ # print(f"Starting Email Sender API Service locally on port {api_port}...")
152
+ # # ... (rest of the local startup print messages and app.run) ...
153
+ # app.run(host='0.0.0.0', port=api_port, debug=True)