Мои эксперименты привели меня к пониманию того, что модуль imaplib может успешно подключаться к серверу электронной почты с использованием протокола IMAP через SSL, когда я активирую свою учетную запись и пароль для сервера Outlook.
Я просто написал программу. Программа демонстрирует, что модуль imaplib подключается к серверу по imaplib.IMAP4_SSL:
Код: Выделить всё
import imaplib
ImapPort = 993
# Connect to the server
mail = imaplib.IMAP4_SSL("outlook.office365.com", ImapPort)
# Login to the account
mail.login(email_user, email_pass)
Код: Выделить всё
> imaplib.IMAP4.error: b'LOGIN failed.'
Код: Выделить всё
# Connect to the server
import imaplib
import logging
import sys
import time
IMAPserver = "outlook.office365.com"
ImapPort = 993
# Configure logging to write to both file and console
log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# Console handler
log_handler_console = logging.StreamHandler(sys.stdout)
log_handler_console.setFormatter(log_formatter)
# Create a logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(log_handler_console)
def connect_to_server(server, port):
try:
mail = imaplib.IMAP4_SSL(server, port)
logging.info(f"Connected to the email server {server}.")
return mail
except imaplib.IMAP4.error as e:
logging.error(f"Connection failed: {str(e)}")
return None
def login_with_retries(server, port, email_user, email_pass, max_retries=30, retry_delay=5):
for attempt in range(max_retries):
mail = connect_to_server(server, port)
if mail is None:
logging.error(f"Retrying connection in {retry_delay} seconds...")
time.sleep(retry_delay)
continue
try:
mail.login(email_user, email_pass)
logging.info(f"Logged into the email account {email_user}.")
return mail # Return the mail object if login is successful
except imaplib.IMAP4.error as e:
logging.error(f"LOGIN failed on attempt {attempt + 1} of {max_retries} (Retry in {retry_delay} seconds). Error: {str(e)}")
mail.logout() # Ensure proper logout before retrying connection
time.sleep(retry_delay)
logging.error("All login attempts failed. Check your email credentials and settings.")
return None # Return False if all attempts fail
try:
# Connect to server
mail = login_with_retries(IMAPserver, ImapPort, email_user, email_pass)
if mail is None:
# Handle login failure
raise RuntimeError("Failed to IMAP login after multiple attempts.")
# Select mailbox
mail.select("inbox")
logging.info("Mailbox inbox folder selected.")
except imaplib.IMAP4.error as e:
logging.error(f"An IMAP error occurred: {e}", exc_info=True)
sys.exit(1)
except Exception as e:
logging.error(f"An unexpected error occurred: {e}", exc_info=True)
sys.exit(1)
Код: Выделить всё
2024-09-04 10:29:34 - INFO - Connected to the email server outlook.office365.com.
2024-09-04 10:29:38 - ERROR - LOGIN failed on attempt 1 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-09-04 10:29:43 - INFO - Connected to the email server outlook.office365.com.
2024-09-04 10:29:47 - ERROR - LOGIN failed on attempt 2 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-09-04 10:29:52 - INFO - Connected to the email server outlook.office365.com.
2024-09-04 10:29:54 - INFO - Logged into the email account s041978@hotmail.com.
2024-09-04 10:29:54 - INFO - Mailbox inbox folder selected.
Подробнее здесь: https://stackoverflow.com/questions/789 ... look-via-i