Я использую Python 3.10 на рабочем столе Ubuntu 22. Я запускаю приведенный ниже код. В коде я пытаюсь переместить электронное письмо из одной почтовой папки Yahoo в другую папку. Код делает это, копируя электронное письмо в новую папку, а затем помечая его для удаления в старой папке. Когда я запускаю код, я получаю сообщение об ошибке ниже. Кто-нибудь знает, в чем проблема, и можете ли вы подсказать, как ее исправить?
код:
import imaplib
import email
from email.header import decode_header
from datetime import datetime, timedelta
import pandas as pd
# Login credentials
user, password = "[email protected]", "xxxxxx"
imap_url = 'imap.mail.yahoo.com'
# Connect to the mail server
my_mail = imaplib.IMAP4_SSL(imap_url)
my_mail.login(user, password)
# move emails from one folder to another
# import imaplib
# Define the target folder to move emails to
target_folder = '"test011325"'
# Ensure the target folder exists
try:
my_mail.select(target_folder)
except imaplib.IMAP4.error:
print(f"Error: Target folder {target_folder} does not exist.")
my_mail.logout()
exit()
# Testing
mail_id_list = [b'8176']
# Move each email from mail_id_list
for mail_id in mail_id_list:
# Ensure the mail ID is in string format
mail_id_str = mail_id.decode()
# Copy the email to the target folder
copy_response = my_mail.copy(mail_id_str, target_folder)
if copy_response[0] != 'OK':
print(f"Failed to copy email with ID {mail_id_str}")
continue
# Mark the email for deletion in the original folder
store_response = my_mail.store(mail_id_str, '+FLAGS', '\\Deleted')
if store_response[0] != 'OK':
print(f"Failed to mark email with ID {mail_id_str} for deletion")
continue
# Permanently delete emails marked as \\Deleted
expunge_response = my_mail.expunge()
if expunge_response[0] == 'OK':
print("Emails moved successfully.")
else:
print("Failed to expunge emails.")
# Logout
my_mail.logout()
ошибка:
---------------------------------------------------------------------------
error Traceback (most recent call last)
in
15
16 # Mark the email for deletion in the original folder
---> 17 store_response = my_mail.store(mail_id_str, '+FLAGS', '\\\\Deleted')
18 if store_response[0] != 'OK':
19 print(f"Failed to mark email with ID {mail_id_str} for deletion")
~/anaconda3/envs/web_scrape_etl/lib/python3.7/imaplib.py in store(self, message_set, command, flags)
838 if (flags[0],flags[-1]) != ('(',')'):
839 flags = '(%s)' % flags # Avoid quoting the flags
--> 840 typ, dat = self._simple_command('STORE', message_set, command, flags)
841 return self._untagged_response(typ, dat, 'FETCH')
842
~/anaconda3/envs/web_scrape_etl/lib/python3.7/imaplib.py in _simple_command(self, name, *args)
1194 def _simple_command(self, name, *args):
1195
-> 1196 return self._command_complete(name, self._command(name, *args))
1197
1198
~/anaconda3/envs/web_scrape_etl/lib/python3.7/imaplib.py in _command_complete(self, name, tag)
1025 self._check_bye()
1026 if typ == 'BAD':
-> 1027 raise self.error('%s command error: %s %s' % (name, typ, data))
1028 return typ, data
1029
error: STORE command error: BAD [b'[CLIENTBUG] STORE Command arguments invalid']
обновление:
Я добавил более подробную отладку, как предложено ниже.
код:
import imaplib
import email
from email.header import decode_header
from datetime import datetime, timedelta
import pandas as pd
# Login credentials
user, password = "[email protected]", "xxxxxx"
imap_url = 'imap.mail.yahoo.com'
# Connect to the mail server
my_mail = imaplib.IMAP4_SSL(imap_url)
my_mail.login(user, password)
# Set the debug level (higher values produce more output)
my_mail.debug = 4
# move emails from one folder to another
# import imaplib
# Define the target folder to move emails to
target_folder = '"test011325"'
# Ensure the target folder exists
try:
my_mail.select(target_folder)
except imaplib.IMAP4.error:
print(f"Error: Target folder {target_folder} does not exist.")
my_mail.logout()
exit()
# Testing
mail_id_list = [b'8176']
# Move each email from mail_id_list
for mail_id in mail_id_list:
# Ensure the mail ID is in string format
mail_id_str = mail_id.decode()
# Copy the email to the target folder
copy_response = my_mail.copy(mail_id_str, target_folder)
if copy_response[0] != 'OK':
print(f"Failed to copy email with ID {mail_id_str}")
continue
# Mark the email for deletion in the original folder
store_response = my_mail.store(mail_id_str, '+FLAGS', '\\Deleted')
if store_response[0] != 'OK':
print(f"Failed to mark email with ID {mail_id_str} for deletion")
continue
# Permanently delete emails marked as \\Deleted
expunge_response = my_mail.expunge()
if expunge_response[0] == 'OK':
print("Emails moved successfully.")
else:
print("Failed to expunge emails.")
# Logout
my_mail.logout()
ошибка:
46:43.54 > b'LPBI2 SELECT "test011325"'
46:44.29 < b'* 0 EXISTS'
46:44.29 < b'* 0 RECENT'
46:44.29 < b'* OK [UIDVALIDITY 1736816455] UIDs valid'
46:44.29 < b'* OK [UIDNEXT 1] Predicted next UID'
46:44.29 < b'* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded $Junk $NotJunk)'
46:44.29 < b'* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded $Junk $NotJunk)] Permanent flags'
46:44.29 < b'* OK [HIGHESTMODSEQ 1]'
46:44.30 < b'* OK [MAILBOXID (150)] Ok'
46:44.57 < b'LPBI2 OK [READ-WRITE] SELECT completed; now in selected state'
46:44.57 > b'LPBI3 COPY 8176 "test011325"'
46:44.98 < b'LPBI3 OK COPY completed'
46:44.98 > b'LPBI4 STORE 8176 +FLAGS (\\Deleted)'
46:49.28 < b'LPBI4 BAD [CLIENTBUG] STORE Bad sequence in the command'
---------------------------------------------------------------------------
error Traceback (most recent call last)
in
53
54 # Mark the email for deletion in the original folder
---> 55 store_response = my_mail.store(mail_id_str, '+FLAGS', '\\Deleted')
56 if store_response[0] != 'OK':
57 print(f"Failed to mark email with ID {mail_id_str} for deletion")
~/anaconda3/envs/web_scrape_etl/lib/python3.7/imaplib.py in store(self, message_set, command, flags)
838 if (flags[0],flags[-1]) != ('(',')'):
839 flags = '(%s)' % flags # Avoid quoting the flags
--> 840 typ, dat = self._simple_command('STORE', message_set, command, flags)
841 return self._untagged_response(typ, dat, 'FETCH')
842
~/anaconda3/envs/web_scrape_etl/lib/python3.7/imaplib.py in _simple_command(self, name, *args)
1194 def _simple_command(self, name, *args):
1195
-> 1196 return self._command_complete(name, self._command(name, *args))
1197
1198
~/anaconda3/envs/web_scrape_etl/lib/python3.7/imaplib.py in _command_complete(self, name, tag)
1025 self._check_bye()
1026 if typ == 'BAD':
-> 1027 raise self.error('%s command error: %s %s' % (name, typ, data))
1028 return typ, data
1029
error: STORE command error: BAD [b'[CLIENTBUG] STORE Bad sequence in the command']
обновить
это сработало
import imaplib
import email
from email.header import decode_header
from datetime import datetime, timedelta
# Login credentials
user, password = "[email protected]", "xxxxxx"
imap_url = 'imap.mail.yahoo.com'
# Connect to the mail server
my_mail = imaplib.IMAP4_SSL(imap_url)
my_mail.login(user, password)
# Select the mailbox folder source folder
folder_name = '"username2012"'
my_mail.select(folder_name)
six_months_ago = (datetime.now() - timedelta(days=180)).strftime('%d-%b-%Y')
# Search for emails received since 6 months ago
_, data = my_mail.uid('SEARCH', None, 'SINCE', six_months_ago)
mail_id_list = data[0].split()
# Testing with the first email
if mail_id_list:
mail_id = mail_id_list[0] # Use UID
# Fetch the email by UID
typ, data = my_mail.uid('FETCH', mail_id, '(RFC822)')
if typ == 'OK' and data:
raw_email = data[0][1]
msg = email.message_from_bytes(raw_email)
# Extract and decode the subject line
raw_subject = msg['Subject']
if raw_subject:
decoded_subject, encoding = decode_header(raw_subject)[0]
if isinstance(decoded_subject, bytes):
decoded_subject = decoded_subject.decode(encoding or 'utf-8')
else:
decoded_subject = 'NA'
# Validation: Print the subject and UID of the email to copy
print('Subject:', decoded_subject)
print('UID:', mail_id.decode('utf-8'))
# Destination folder to copy email to
target_folder = '"test011325"'
# Copy the email to the target folder
copy_response = my_mail.uid("COPY", mail_id, target_folder)
if copy_response[0] == 'OK':
print(f"Email successfully copied to {target_folder}")
else:
print(f"Failed to copy email to {target_folder}: {copy_response}")
else:
print("Failed to fetch the email.")
else:
print("No emails found in the source folder.")
# Logout
my_mail.logout()
Подробнее здесь: https://stackoverflow.com/questions/793 ... to-another
Переместить электронную почту из одной папки Yahoo в другую ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение