如何解决同时使用IMAP从gmail提取邮件
我想从Gmail中通过其ID提取多封邮件,为此我正在使用Imap。 直到我尝试使用ThreadPull执行器(甚至是2个执行器)加快运行速度时,它的效果都很好。
如果任何人都可以考虑导致该问题的原因,那将非常有帮助。
connector.py
def create_data_models(self,msgs_ids,max_workers=2):
data_models = []
#msgs_id_list = [message['id'] for message in messages]
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(self.imapService.fetch_message,msg_id) : msg_id for msg_id in msgs_ids}
for future in concurrent.futures.as_completed(futures):
try:
data = future.result()
data_model = self._create_msg_obj1(data)
data_models.append(data_model)
except Exception as exc:
print('generated an exception: %s' % (exc))
return data_models
imap_service.py
def fetch_message(self,msg_id):
_,data = self.mail.uid('fetch',msg_id,'(RFC822)')
_,mail_data = data[0]
logger.error('Succesfully fetch message from {} with {} id'.format(self.email_address,msg_id))
print('Succesfully fetch message from {} with {} id'.format(self.email_address,msg_id))
return mail_data
错误:
generated an exception: command: UID => unexpected response: b'v5oJ8jIW2KPDzS/DHMN+58yL3Q'
generated an exception: command: UID => unexpected response: b'X-Google-Smtp-Source: APXvYqwtp0c9H1jJ8uZTRW5ZBjIyNbqRgeoGUq8heUUf00uNRHW9Nvyl1dTjYZAy6ijzL29+PTL7'
generated an exception: command: UID => unexpected response: b'X-Received: by 2002:a50:9223:: with SMTP id i32mr19845429eda.40.1566127216934;'
generated an exception: command: UID => unexpected response: b' Sun,18 Aug 2019 04:20:16 -0700 (PDT)'
generated an exception: command: UID => unexpected response: b'le.com; s=arc-20160816;'
generated an exception: command: UID => unexpected response: b' h=message-id:to:sender:from:reply-to:subject:date:mime-version'
解决方法
使用此
import imaplib
import email
host = input('Your Hostname: ')
username = input('Your Username: ')
password = input('Your Password: ')
def get_inbox():
mail = imaplib.IMAP4_SSL(host)
mail.login(username,password)
mail.select("inbox")
_,search_data = mail.search(None,'SEEN')
my_message = []
for num in search_data[0].split():
email_data = {}
_,data = mail.fetch(num,'(RFC822)')
# print(data[0])
_,b = data[0]
email_message = email.message_from_bytes(b)
for header in ['subject','to','from','date']:
print("{}: {}".format(header,email_message[header]))
email_data[header] = email_message[header]
for part in email_message.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True)
email_data['body'] = body.decode()
elif part.get_content_type() == "text/html":
html_body = part.get_payload(decode=True)
email_data['html_body'] = html_body.decode()
my_message.append(email_data)
return my_message
if __name__ == "__main__":
my_inbox = get_inbox()
print(my_inbox)
# print(search_data)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。