Upload 21 files
Browse files- email_config_ruy.py +96 -0
- email_ecg_processor.py +185 -24
- test_email_connection.py +145 -0
email_config_ruy.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
RUY.APP Email Configuration Helper
|
| 3 |
+
Ubden® Team - Specific configuration for ruy.app email domain
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
class RuyAppEmailConfig:
|
| 12 |
+
"""Configuration helper for ruy.app email domain"""
|
| 13 |
+
|
| 14 |
+
@staticmethod
|
| 15 |
+
def get_email_settings():
|
| 16 |
+
"""Get email settings for ruy.app domain"""
|
| 17 |
+
|
| 18 |
+
# ruy.app email configuration
|
| 19 |
+
# Based on the screenshot showing POP3, IMAP, SMTP settings
|
| 20 |
+
config = {
|
| 21 |
+
'imap_host': 'ruy.app', # Try direct domain first
|
| 22 |
+
'imap_port': 993, # Standard IMAP SSL port
|
| 23 |
+
'imap_ssl': True,
|
| 24 |
+
|
| 25 |
+
'smtp_host': 'ruy.app', # Try direct domain first
|
| 26 |
+
'smtp_port': 465, # Try SSL SMTP port first
|
| 27 |
+
'smtp_ssl': True,
|
| 28 |
+
|
| 29 |
+
# Alternative configurations to try
|
| 30 |
+
'alternatives': [
|
| 31 |
+
# Try with mail. prefix
|
| 32 |
+
{
|
| 33 |
+
'imap_host': 'mail.ruy.app',
|
| 34 |
+
'smtp_host': 'mail.ruy.app',
|
| 35 |
+
'imap_port': 993,
|
| 36 |
+
'smtp_port': 465,
|
| 37 |
+
},
|
| 38 |
+
# Try with imap./smtp. prefixes
|
| 39 |
+
{
|
| 40 |
+
'imap_host': 'imap.ruy.app',
|
| 41 |
+
'smtp_host': 'smtp.ruy.app',
|
| 42 |
+
'imap_port': 993,
|
| 43 |
+
'smtp_port': 587, # Try STARTTLS port
|
| 44 |
+
},
|
| 45 |
+
# Try non-SSL ports
|
| 46 |
+
{
|
| 47 |
+
'imap_host': 'ruy.app',
|
| 48 |
+
'smtp_host': 'ruy.app',
|
| 49 |
+
'imap_port': 143, # Non-SSL IMAP
|
| 50 |
+
'smtp_port': 587, # STARTTLS SMTP
|
| 51 |
+
},
|
| 52 |
+
]
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
return config
|
| 56 |
+
|
| 57 |
+
@staticmethod
|
| 58 |
+
def setup_environment_for_ruy_app():
|
| 59 |
+
"""Setup environment variables for ruy.app"""
|
| 60 |
+
|
| 61 |
+
# Set default values if not already set
|
| 62 |
+
if not os.getenv('mail_host'):
|
| 63 |
+
os.environ['mail_host'] = 'ruy.app'
|
| 64 |
+
|
| 65 |
+
if not os.getenv('IMAP_PORT'):
|
| 66 |
+
os.environ['IMAP_PORT'] = '993'
|
| 67 |
+
|
| 68 |
+
if not os.getenv('SMTP_HOST'):
|
| 69 |
+
os.environ['SMTP_HOST'] = 'ruy.app'
|
| 70 |
+
|
| 71 |
+
if not os.getenv('SMTP_PORT'):
|
| 72 |
+
os.environ['SMTP_PORT'] = '465'
|
| 73 |
+
|
| 74 |
+
logger.info("🔧 RUY.APP email configuration applied")
|
| 75 |
+
|
| 76 |
+
return {
|
| 77 |
+
'mail_host': os.getenv('mail_host'),
|
| 78 |
+
'imap_port': os.getenv('IMAP_PORT'),
|
| 79 |
+
'smtp_host': os.getenv('SMTP_HOST'),
|
| 80 |
+
'smtp_port': os.getenv('SMTP_PORT'),
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
def detect_and_configure_ruy_app():
|
| 84 |
+
"""Auto-detect and configure ruy.app email settings"""
|
| 85 |
+
|
| 86 |
+
mail_username = os.getenv('mail_username', '')
|
| 87 |
+
|
| 88 |
+
if 'ruy.app' in mail_username.lower():
|
| 89 |
+
logger.info("🎯 Detected ruy.app email domain - applying specific configuration")
|
| 90 |
+
return RuyAppEmailConfig.setup_environment_for_ruy_app()
|
| 91 |
+
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
# Auto-configure if this module is imported
|
| 95 |
+
if __name__ != "__main__":
|
| 96 |
+
detect_and_configure_ruy_app()
|
email_ecg_processor.py
CHANGED
|
@@ -20,6 +20,13 @@ from email.header import decode_header
|
|
| 20 |
from typing import Dict, List, Any, Optional, Tuple
|
| 21 |
import logging
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# Configure logging
|
| 24 |
logging.basicConfig(
|
| 25 |
level=logging.INFO,
|
|
@@ -36,6 +43,12 @@ class EmailECGProcessor:
|
|
| 36 |
|
| 37 |
def __init__(self):
|
| 38 |
"""Initialize with environment variables"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
self.mail_host = os.getenv('mail_host', 'imap.gmail.com')
|
| 40 |
self.mail_username = os.getenv('mail_username')
|
| 41 |
self.mail_password = os.getenv('mail_pw')
|
|
@@ -46,9 +59,9 @@ class EmailECGProcessor:
|
|
| 46 |
self.endpoint_url = self._get_endpoint_url()
|
| 47 |
|
| 48 |
# Email configuration
|
| 49 |
-
self.smtp_host = self.
|
| 50 |
-
self.smtp_port = 587
|
| 51 |
-
self.imap_port = 993
|
| 52 |
|
| 53 |
# Processing configuration
|
| 54 |
self.max_retries = 3
|
|
@@ -85,6 +98,38 @@ class EmailECGProcessor:
|
|
| 85 |
|
| 86 |
raise ValueError("PULSE_ENDPOINT_URL, HF_SPACE_NAME, or ENDPOINT_NAME must be set in environment variables")
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def _validate_configuration(self):
|
| 89 |
"""Validate required environment variables"""
|
| 90 |
required_vars = {
|
|
@@ -100,16 +145,140 @@ class EmailECGProcessor:
|
|
| 100 |
logger.info("✅ Configuration validation passed")
|
| 101 |
|
| 102 |
def connect_to_email(self) -> imaplib.IMAP4_SSL:
|
| 103 |
-
"""Connect to email server"""
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
def get_unread_emails(self, mail: imaplib.IMAP4_SSL) -> List[str]:
|
| 115 |
"""Get list of unread email IDs"""
|
|
@@ -327,12 +496,8 @@ Geçmiş olsun! 🙏
|
|
| 327 |
|
| 328 |
msg.attach(MIMEText(body, 'plain', 'utf-8'))
|
| 329 |
|
| 330 |
-
# Send email
|
| 331 |
-
|
| 332 |
-
server.starttls()
|
| 333 |
-
server.login(self.mail_username, self.mail_password)
|
| 334 |
-
server.send_message(msg)
|
| 335 |
-
server.quit()
|
| 336 |
|
| 337 |
logger.info(f"✅ Analysis result sent to {recipient}")
|
| 338 |
return True
|
|
@@ -389,11 +554,7 @@ Problem devam ederse lütfen sistem yöneticisi ile iletişime geçin.
|
|
| 389 |
|
| 390 |
msg.attach(MIMEText(body, 'plain', 'utf-8'))
|
| 391 |
|
| 392 |
-
|
| 393 |
-
server.starttls()
|
| 394 |
-
server.login(self.mail_username, self.mail_password)
|
| 395 |
-
server.send_message(msg)
|
| 396 |
-
server.quit()
|
| 397 |
|
| 398 |
logger.info(f"📧 Error notification sent to {recipient}")
|
| 399 |
return True
|
|
|
|
| 20 |
from typing import Dict, List, Any, Optional, Tuple
|
| 21 |
import logging
|
| 22 |
|
| 23 |
+
# Try to import ruy.app specific configuration
|
| 24 |
+
try:
|
| 25 |
+
from email_config_ruy import detect_and_configure_ruy_app, RuyAppEmailConfig
|
| 26 |
+
RUY_CONFIG_AVAILABLE = True
|
| 27 |
+
except ImportError:
|
| 28 |
+
RUY_CONFIG_AVAILABLE = False
|
| 29 |
+
|
| 30 |
# Configure logging
|
| 31 |
logging.basicConfig(
|
| 32 |
level=logging.INFO,
|
|
|
|
| 43 |
|
| 44 |
def __init__(self):
|
| 45 |
"""Initialize with environment variables"""
|
| 46 |
+
# Auto-configure for ruy.app if detected
|
| 47 |
+
if RUY_CONFIG_AVAILABLE:
|
| 48 |
+
ruy_config = detect_and_configure_ruy_app()
|
| 49 |
+
if ruy_config:
|
| 50 |
+
logger.info("🎯 Applied ruy.app specific configuration")
|
| 51 |
+
|
| 52 |
self.mail_host = os.getenv('mail_host', 'imap.gmail.com')
|
| 53 |
self.mail_username = os.getenv('mail_username')
|
| 54 |
self.mail_password = os.getenv('mail_pw')
|
|
|
|
| 59 |
self.endpoint_url = self._get_endpoint_url()
|
| 60 |
|
| 61 |
# Email configuration
|
| 62 |
+
self.smtp_host = self._get_smtp_host()
|
| 63 |
+
self.smtp_port = int(os.getenv('SMTP_PORT', '587'))
|
| 64 |
+
self.imap_port = int(os.getenv('IMAP_PORT', '993'))
|
| 65 |
|
| 66 |
# Processing configuration
|
| 67 |
self.max_retries = 3
|
|
|
|
| 98 |
|
| 99 |
raise ValueError("PULSE_ENDPOINT_URL, HF_SPACE_NAME, or ENDPOINT_NAME must be set in environment variables")
|
| 100 |
|
| 101 |
+
def _get_smtp_host(self) -> str:
|
| 102 |
+
"""Get SMTP host based on IMAP host or environment variable"""
|
| 103 |
+
# Check if SMTP host is explicitly set
|
| 104 |
+
smtp_host = os.getenv('SMTP_HOST')
|
| 105 |
+
if smtp_host:
|
| 106 |
+
return smtp_host
|
| 107 |
+
|
| 108 |
+
# Try to derive SMTP host from IMAP host
|
| 109 |
+
if not self.mail_host:
|
| 110 |
+
return 'smtp.gmail.com' # Default fallback
|
| 111 |
+
|
| 112 |
+
# Common email provider mappings
|
| 113 |
+
host_mappings = {
|
| 114 |
+
'imap.gmail.com': 'smtp.gmail.com',
|
| 115 |
+
'outlook.office365.com': 'smtp-mail.outlook.com',
|
| 116 |
+
'imap.mail.yahoo.com': 'smtp.mail.yahoo.com',
|
| 117 |
+
'imap.yandex.com': 'smtp.yandex.com',
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
# Check for exact matches
|
| 121 |
+
if self.mail_host in host_mappings:
|
| 122 |
+
return host_mappings[self.mail_host]
|
| 123 |
+
|
| 124 |
+
# For custom domains, try common patterns
|
| 125 |
+
if 'imap.' in self.mail_host:
|
| 126 |
+
return self.mail_host.replace('imap.', 'smtp.')
|
| 127 |
+
elif 'mail.' in self.mail_host:
|
| 128 |
+
return self.mail_host.replace('mail.', 'smtp.')
|
| 129 |
+
else:
|
| 130 |
+
# If it's a custom domain, try adding smtp prefix
|
| 131 |
+
return f"smtp.{self.mail_host}"
|
| 132 |
+
|
| 133 |
def _validate_configuration(self):
|
| 134 |
"""Validate required environment variables"""
|
| 135 |
required_vars = {
|
|
|
|
| 145 |
logger.info("✅ Configuration validation passed")
|
| 146 |
|
| 147 |
def connect_to_email(self) -> imaplib.IMAP4_SSL:
|
| 148 |
+
"""Connect to email server with multiple retry strategies"""
|
| 149 |
+
|
| 150 |
+
# Check if this is ruy.app and get specific configurations
|
| 151 |
+
if RUY_CONFIG_AVAILABLE and 'ruy.app' in self.mail_username.lower():
|
| 152 |
+
ruy_settings = RuyAppEmailConfig.get_email_settings()
|
| 153 |
+
connection_attempts = [
|
| 154 |
+
# Try main ruy.app configuration
|
| 155 |
+
{'host': ruy_settings['imap_host'], 'use_ssl': True, 'port': ruy_settings['imap_port'], 'timeout': 60},
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
# Add alternative configurations
|
| 159 |
+
for alt in ruy_settings['alternatives']:
|
| 160 |
+
connection_attempts.append({
|
| 161 |
+
'host': alt['imap_host'],
|
| 162 |
+
'use_ssl': True,
|
| 163 |
+
'port': alt['imap_port'],
|
| 164 |
+
'timeout': 60
|
| 165 |
+
})
|
| 166 |
+
else:
|
| 167 |
+
# Standard connection attempts for other providers
|
| 168 |
+
connection_attempts = [
|
| 169 |
+
# Attempt 1: Standard SSL connection
|
| 170 |
+
{'host': self.mail_host, 'use_ssl': True, 'port': self.imap_port, 'timeout': 30},
|
| 171 |
+
# Attempt 2: Try alternative SSL port
|
| 172 |
+
{'host': self.mail_host, 'use_ssl': True, 'port': 993, 'timeout': 60},
|
| 173 |
+
# Attempt 3: Try with different timeout
|
| 174 |
+
{'host': self.mail_host, 'use_ssl': True, 'port': self.imap_port, 'timeout': 120},
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
last_error = None
|
| 178 |
+
|
| 179 |
+
for i, attempt in enumerate(connection_attempts):
|
| 180 |
+
try:
|
| 181 |
+
host = attempt.get('host', self.mail_host)
|
| 182 |
+
logger.info(f"🔄 Connection attempt {i+1}: {host}:{attempt['port']} (SSL: {attempt['use_ssl']}, Timeout: {attempt['timeout']}s)")
|
| 183 |
+
|
| 184 |
+
if attempt['use_ssl']:
|
| 185 |
+
# Try SSL connection
|
| 186 |
+
mail = imaplib.IMAP4_SSL(host, attempt['port'])
|
| 187 |
+
# Set socket timeout
|
| 188 |
+
mail.sock.settimeout(attempt['timeout'])
|
| 189 |
+
else:
|
| 190 |
+
# Try non-SSL connection (fallback)
|
| 191 |
+
mail = imaplib.IMAP4(host, attempt['port'])
|
| 192 |
+
mail.sock.settimeout(attempt['timeout'])
|
| 193 |
+
|
| 194 |
+
# Try to login
|
| 195 |
+
mail.login(self.mail_username, self.mail_password)
|
| 196 |
+
mail.select('INBOX')
|
| 197 |
+
|
| 198 |
+
logger.info(f"✅ Connected to email server: {host}:{attempt['port']}")
|
| 199 |
+
return mail
|
| 200 |
+
|
| 201 |
+
except Exception as e:
|
| 202 |
+
last_error = e
|
| 203 |
+
logger.warning(f"⚠️ Connection attempt {i+1} failed: {e}")
|
| 204 |
+
|
| 205 |
+
# Clean up failed connection
|
| 206 |
+
try:
|
| 207 |
+
if 'mail' in locals():
|
| 208 |
+
mail.logout()
|
| 209 |
+
except:
|
| 210 |
+
pass
|
| 211 |
+
|
| 212 |
+
# All attempts failed
|
| 213 |
+
logger.error(f"❌ All connection attempts failed. Last error: {last_error}")
|
| 214 |
+
|
| 215 |
+
# Provide helpful troubleshooting info
|
| 216 |
+
logger.info("🔧 Troubleshooting tips:")
|
| 217 |
+
logger.info(f" - Check if IMAP is enabled for {self.mail_username}")
|
| 218 |
+
logger.info(f" - Verify mail_host: {self.mail_host}")
|
| 219 |
+
logger.info(f" - Check firewall/network connectivity")
|
| 220 |
+
logger.info(f" - Try different ports: 993, 143")
|
| 221 |
+
|
| 222 |
+
raise last_error
|
| 223 |
+
|
| 224 |
+
def _send_email_with_retry(self, msg):
|
| 225 |
+
"""Send email with retry logic for different SMTP configurations"""
|
| 226 |
+
|
| 227 |
+
# Get SMTP configurations to try
|
| 228 |
+
if RUY_CONFIG_AVAILABLE and 'ruy.app' in self.mail_username.lower():
|
| 229 |
+
ruy_settings = RuyAppEmailConfig.get_email_settings()
|
| 230 |
+
smtp_attempts = [
|
| 231 |
+
{'host': ruy_settings['smtp_host'], 'port': ruy_settings['smtp_port'], 'use_ssl': True},
|
| 232 |
+
]
|
| 233 |
+
|
| 234 |
+
# Add alternatives
|
| 235 |
+
for alt in ruy_settings['alternatives']:
|
| 236 |
+
smtp_attempts.append({
|
| 237 |
+
'host': alt['smtp_host'],
|
| 238 |
+
'port': alt['smtp_port'],
|
| 239 |
+
'use_ssl': alt['smtp_port'] == 465 # SSL for port 465, STARTTLS for 587
|
| 240 |
+
})
|
| 241 |
+
else:
|
| 242 |
+
# Standard SMTP configurations
|
| 243 |
+
smtp_attempts = [
|
| 244 |
+
{'host': self.smtp_host, 'port': self.smtp_port, 'use_ssl': self.smtp_port == 465},
|
| 245 |
+
{'host': self.smtp_host, 'port': 587, 'use_ssl': False}, # Try STARTTLS
|
| 246 |
+
{'host': self.smtp_host, 'port': 465, 'use_ssl': True}, # Try SSL
|
| 247 |
+
]
|
| 248 |
+
|
| 249 |
+
last_error = None
|
| 250 |
+
|
| 251 |
+
for i, attempt in enumerate(smtp_attempts):
|
| 252 |
+
try:
|
| 253 |
+
logger.info(f"🔄 SMTP attempt {i+1}: {attempt['host']}:{attempt['port']} (SSL: {attempt['use_ssl']})")
|
| 254 |
+
|
| 255 |
+
if attempt['use_ssl']:
|
| 256 |
+
# Use SSL connection
|
| 257 |
+
server = smtplib.SMTP_SSL(attempt['host'], attempt['port'])
|
| 258 |
+
else:
|
| 259 |
+
# Use STARTTLS
|
| 260 |
+
server = smtplib.SMTP(attempt['host'], attempt['port'])
|
| 261 |
+
server.starttls()
|
| 262 |
+
|
| 263 |
+
server.login(self.mail_username, self.mail_password)
|
| 264 |
+
server.send_message(msg)
|
| 265 |
+
server.quit()
|
| 266 |
+
|
| 267 |
+
logger.info(f"✅ Email sent via {attempt['host']}:{attempt['port']}")
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
except Exception as e:
|
| 271 |
+
last_error = e
|
| 272 |
+
logger.warning(f"⚠️ SMTP attempt {i+1} failed: {e}")
|
| 273 |
+
|
| 274 |
+
try:
|
| 275 |
+
if 'server' in locals():
|
| 276 |
+
server.quit()
|
| 277 |
+
except:
|
| 278 |
+
pass
|
| 279 |
+
|
| 280 |
+
# All attempts failed
|
| 281 |
+
raise last_error
|
| 282 |
|
| 283 |
def get_unread_emails(self, mail: imaplib.IMAP4_SSL) -> List[str]:
|
| 284 |
"""Get list of unread email IDs"""
|
|
|
|
| 496 |
|
| 497 |
msg.attach(MIMEText(body, 'plain', 'utf-8'))
|
| 498 |
|
| 499 |
+
# Send email with improved connection handling
|
| 500 |
+
self._send_email_with_retry(msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
|
| 502 |
logger.info(f"✅ Analysis result sent to {recipient}")
|
| 503 |
return True
|
|
|
|
| 554 |
|
| 555 |
msg.attach(MIMEText(body, 'plain', 'utf-8'))
|
| 556 |
|
| 557 |
+
self._send_email_with_retry(msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
logger.info(f"📧 Error notification sent to {recipient}")
|
| 560 |
return True
|
test_email_connection.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Email Connection Test for RUY.APP
|
| 4 |
+
Ubden® Team - Test email connectivity before running full processor
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import logging
|
| 10 |
+
from email_ecg_processor import EmailECGProcessor
|
| 11 |
+
|
| 12 |
+
# Configure logging
|
| 13 |
+
logging.basicConfig(
|
| 14 |
+
level=logging.INFO,
|
| 15 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 16 |
+
)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
def test_email_connection():
|
| 20 |
+
"""Test email connection with current configuration"""
|
| 21 |
+
|
| 22 |
+
print("🧪 Testing Email Connection for RUY.APP")
|
| 23 |
+
print("=" * 50)
|
| 24 |
+
|
| 25 |
+
# Check environment variables
|
| 26 |
+
required_vars = ['mail_username', 'mail_pw']
|
| 27 |
+
missing_vars = [var for var in required_vars if not os.getenv(var)]
|
| 28 |
+
|
| 29 |
+
if missing_vars:
|
| 30 |
+
print(f"❌ Missing environment variables: {', '.join(missing_vars)}")
|
| 31 |
+
print("\n📋 Required Environment Variables:")
|
| 32 |
+
print("export mail_username='[email protected]'")
|
| 33 |
+
print("export mail_pw='your_password'")
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
# Show current configuration
|
| 37 |
+
print(f"📧 Testing connection for: {os.getenv('mail_username')}")
|
| 38 |
+
print(f"🏠 Mail host: {os.getenv('mail_host', 'auto-detected')}")
|
| 39 |
+
print(f"🔌 IMAP port: {os.getenv('IMAP_PORT', 'auto-detected')}")
|
| 40 |
+
print(f"📤 SMTP host: {os.getenv('SMTP_HOST', 'auto-detected')}")
|
| 41 |
+
print(f"🔌 SMTP port: {os.getenv('SMTP_PORT', 'auto-detected')}")
|
| 42 |
+
print()
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
# Initialize processor (this will auto-configure ruy.app settings)
|
| 46 |
+
print("🔧 Initializing email processor...")
|
| 47 |
+
processor = EmailECGProcessor()
|
| 48 |
+
|
| 49 |
+
# Test IMAP connection
|
| 50 |
+
print("📥 Testing IMAP connection...")
|
| 51 |
+
mail = processor.connect_to_email()
|
| 52 |
+
|
| 53 |
+
# Test basic operations
|
| 54 |
+
print("📬 Testing email operations...")
|
| 55 |
+
unread_emails = processor.get_unread_emails(mail)
|
| 56 |
+
print(f"✅ Found {len(unread_emails)} unread emails")
|
| 57 |
+
|
| 58 |
+
# Close connection
|
| 59 |
+
mail.close()
|
| 60 |
+
mail.logout()
|
| 61 |
+
print("✅ IMAP connection test successful!")
|
| 62 |
+
|
| 63 |
+
# Test SMTP by sending a test email to self
|
| 64 |
+
print("📤 Testing SMTP connection...")
|
| 65 |
+
test_msg_content = """
|
| 66 |
+
Konu: 🧪 Email Connection Test
|
| 67 |
+
|
| 68 |
+
Bu bir test mesajıdır. Email sistemi çalışıyor!
|
| 69 |
+
|
| 70 |
+
Test zamanı: {timestamp}
|
| 71 |
+
|
| 72 |
+
---
|
| 73 |
+
PULSE-7B Email ECG Processor Test
|
| 74 |
+
""".format(timestamp=__import__('datetime').datetime.now())
|
| 75 |
+
|
| 76 |
+
# Create a simple test message
|
| 77 |
+
from email.mime.text import MIMEText
|
| 78 |
+
from email.mime.multipart import MIMEMultipart
|
| 79 |
+
|
| 80 |
+
test_msg = MIMEMultipart()
|
| 81 |
+
test_msg['From'] = processor.mail_username
|
| 82 |
+
test_msg['To'] = processor.mail_username # Send to self
|
| 83 |
+
test_msg['Subject'] = "🧪 PULSE-7B Email Test"
|
| 84 |
+
test_msg.attach(MIMEText(test_msg_content, 'plain', 'utf-8'))
|
| 85 |
+
|
| 86 |
+
processor._send_email_with_retry(test_msg)
|
| 87 |
+
print("✅ SMTP connection test successful!")
|
| 88 |
+
|
| 89 |
+
print("\n🎉 All tests passed! Email system is working correctly.")
|
| 90 |
+
print("📧 You should receive a test email shortly.")
|
| 91 |
+
return True
|
| 92 |
+
|
| 93 |
+
except Exception as e:
|
| 94 |
+
print(f"\n❌ Connection test failed: {e}")
|
| 95 |
+
print("\n🔧 Troubleshooting suggestions:")
|
| 96 |
+
print("1. Check if email credentials are correct")
|
| 97 |
+
print("2. Verify that IMAP/SMTP is enabled for your account")
|
| 98 |
+
print("3. Check firewall/network connectivity")
|
| 99 |
+
print("4. Try different ports (993, 143 for IMAP; 465, 587 for SMTP)")
|
| 100 |
+
print("5. Contact your email provider for server settings")
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
def show_ruy_app_settings():
|
| 104 |
+
"""Show recommended settings for ruy.app"""
|
| 105 |
+
print("\n📋 Recommended RUY.APP Settings:")
|
| 106 |
+
print("Based on your email provider screenshot:")
|
| 107 |
+
print()
|
| 108 |
+
print("IMAP Settings:")
|
| 109 |
+
print(" - Server: ruy.app (or mail.ruy.app)")
|
| 110 |
+
print(" - Port: 993 (SSL) or 143 (STARTTLS)")
|
| 111 |
+
print(" - Security: SSL/TLS")
|
| 112 |
+
print()
|
| 113 |
+
print("SMTP Settings:")
|
| 114 |
+
print(" - Server: ruy.app (or mail.ruy.app)")
|
| 115 |
+
print(" - Port: 465 (SSL) or 587 (STARTTLS)")
|
| 116 |
+
print(" - Security: SSL/TLS")
|
| 117 |
+
print()
|
| 118 |
+
print("POP3 Settings (if needed):")
|
| 119 |
+
print(" - Server: ruy.app")
|
| 120 |
+
print(" - Port: 995 (SSL)")
|
| 121 |
+
print()
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help', 'help']:
|
| 125 |
+
print("Email Connection Test for RUY.APP")
|
| 126 |
+
print()
|
| 127 |
+
print("Usage:")
|
| 128 |
+
print(" python test_email_connection.py")
|
| 129 |
+
print()
|
| 130 |
+
print("Environment Variables:")
|
| 131 |
+
print(" mail_username - Your ruy.app email address")
|
| 132 |
+
print(" mail_pw - Your email password")
|
| 133 |
+
print()
|
| 134 |
+
show_ruy_app_settings()
|
| 135 |
+
sys.exit(0)
|
| 136 |
+
|
| 137 |
+
success = test_email_connection()
|
| 138 |
+
|
| 139 |
+
if not success:
|
| 140 |
+
show_ruy_app_settings()
|
| 141 |
+
sys.exit(1)
|
| 142 |
+
else:
|
| 143 |
+
print("\n🚀 Ready to run the full email processor!")
|
| 144 |
+
print("Run: python start_email_processor.py")
|
| 145 |
+
sys.exit(0)
|