У меня есть этот код для аутентификации/входа на hotmail.com через IMAP. Я включил пароль приложения для Hotmail/Outlook. Единственная проблема заключается в том, что аутентификация завершается неудачей с сообщением «Ошибка входа» в течение первых 5–10 попыток и, наконец, завершается успешно с тем же паролем приложения. Я не могу понять, почему это происходит.
import logging
import imaplib
import sys
# Your email credentials
email_user = "user1@hotmail.com"
email_pass = "APPPASSWORD"
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:
#print(f"An IMAP error occurred: {e}")
logging.error(f"An IMAP error occurred: {e}", exc_info=True)
wait_with_timeout(sleepError)
sys.exit(1)
except Exception as e:
#print(f"An unexpected error occurred: {e}")
logging.error(f"An unexpected error occurred: {e}", exc_info=True)
wait_with_timeout(sleepError)
sys.exit(1)
Когда я запускаю код, после нескольких попыток я вижу, что он успешен. Не знаете почему?
Вот журнал:
2024-08-01 14:04:49 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:04:51 - ERROR - LOGIN failed on attempt 1 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:04:56 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:04:57 - ERROR - LOGIN failed on attempt 2 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:05:02 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:05:03 - ERROR - LOGIN failed on attempt 3 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:05:09 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:05:10 - ERROR - LOGIN failed on attempt 4 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:05:15 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:05:16 - ERROR - LOGIN failed on attempt 5 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:05:21 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:05:23 - ERROR - LOGIN failed on attempt 6 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:05:28 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:05:29 - ERROR - LOGIN failed on attempt 7 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:05:35 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:05:36 - ERROR - LOGIN failed on attempt 8 of 30 (Retry in 5 seconds). Error: b'LOGIN failed.'
2024-08-01 14:05:41 - INFO - Connected to the email server outlook.office365.com.
2024-08-01 14:05:42 - INFO - Logged into the email account user1@hotmail.com.
2024-08-01 14:05:44 - INFO - Mailbox inbox folder selected.
Подробнее здесь: https://stackoverflow.com/questions/788 ... thenticate
IMAP в Outlook Hotmail требует много попыток (не удалось войти в систему) для аутентификации ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как политики повторных попыток Polly указывают на превышение количества повторных попыток?
Anonymous » » в форуме C# - 0 Ответы
- 19 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как политики повторных попыток Polly указывают на превышение количества повторных попыток?
Anonymous » » в форуме C# - 0 Ответы
- 25 Просмотры
-
Последнее сообщение Anonymous
-
Мобильная версия