Test IMAP and SMTP connections. Returns dict with 'ok' (bool), 'imap' (str), 'smtp' (str) status messages.
(config: dict)
| 411 | |
| 412 | |
| 413 | async def test_connection(config: dict) -> dict: |
| 414 | """Test IMAP and SMTP connections. |
| 415 | |
| 416 | Returns dict with 'ok' (bool), 'imap' (str), 'smtp' (str) status messages. |
| 417 | """ |
| 418 | cfg = resolve_config(config) |
| 419 | addr = cfg["email_address"] |
| 420 | password = cfg["auth_code"] |
| 421 | |
| 422 | if not addr or not password: |
| 423 | return {"ok": False, "error": "Email address and authorization code are required."} |
| 424 | |
| 425 | result = {"ok": True, "imap": "", "smtp": ""} |
| 426 | |
| 427 | # Test IMAP |
| 428 | try: |
| 429 | with force_ipv4(): |
| 430 | context = ssl.create_default_context() |
| 431 | with imaplib.IMAP4_SSL(cfg["imap_host"], cfg["imap_port"], ssl_context=context) as mail: |
| 432 | mail.login(addr, password) |
| 433 | mail.select("INBOX", readonly=True) |
| 434 | _, msg_nums = mail.search(None, "ALL") |
| 435 | count = len(msg_nums[0].split()) if msg_nums[0] else 0 |
| 436 | result["imap"] = f"✅ IMAP connected ({count} emails in INBOX)" |
| 437 | except imaplib.IMAP4.error as e: |
| 438 | result["ok"] = False |
| 439 | result["imap"] = f"❌ IMAP failed: {str(e)[:150]}" |
| 440 | except Exception as e: |
| 441 | result["ok"] = False |
| 442 | result["imap"] = f"❌ IMAP error: {str(e)[:150]}" |
| 443 | |
| 444 | # Test SMTP |
| 445 | try: |
| 446 | send_smtp_email( |
| 447 | host=cfg["smtp_host"], |
| 448 | port=cfg["smtp_port"], |
| 449 | user=addr, |
| 450 | password=password, |
| 451 | from_addr=addr, |
| 452 | to_addrs=[addr], # Send to self for test |
| 453 | msg_string=f"From: {addr}\nTo: {addr}\nSubject: Clawith Connection Test\n\nSMTP Connection Successful.", |
| 454 | use_ssl=cfg.get("smtp_ssl", True), |
| 455 | timeout=10, |
| 456 | ) |
| 457 | result["smtp"] = "✅ SMTP connected" |
| 458 | except smtplib.SMTPAuthenticationError: |
| 459 | result["ok"] = False |
| 460 | result["smtp"] = "❌ SMTP authentication failed" |
| 461 | except Exception as e: |
| 462 | result["ok"] = False |
| 463 | result["smtp"] = f"❌ SMTP error: {str(e)[:150]}" |
| 464 | |
| 465 | return result |
no test coverage detected