0

Pythonでメールを読み込んでいます。
メールの本文から特定の検索用語を取得します。
取得した検索用語をGOOGLEで検索しています。

ただ2件以上のメールがあるとループせず下記のエラー**imaplib.error:**が発生してしまいます。
2件以上のメールがある場合、どのようにループさせるようにすればよろしいでしょうか。

エラー内容

imaplib.error: command FETCH illegal in state LOGOUT, only allowed in states SELECTED

print(kensaku_yougo)

AMERICA

JAPAN

実現したい結果

①メールの本文からAMERICAの用語を取得してその後にGOOGLEで検索
①が終わりましたら②他のメール本文からJAPANの用語を取得してその後にGOOGLEで検索
※未読メールがある度ループさせたいです。

お手数ですが、ご教授お願い致します。

全体のコード

#メール本文からメールアドレス取得----------------------------------------
from smtplib import SMTP
from email.mime.text import MIMEText
from email import encoders
from email.mime.base import MIMEBase
import imaplib, re, email, six, dateutil.parser
from email.mime.multipart import MIMEMultipart
import smtplib
from email.utils import formatdate
import base64
from bs4 import BeautifulSoup
from bs4.element import Comment

mail=imaplib.IMAP4_SSL('imap.gmail.com',993)    #SMTPは993,POPは995
mail.login('example','1234')
mail.select('test') #メールボックスの選択

#UNSEEN未読メールを読み込む
# type,data=mail.search(None,'UNSEEN') #メールボックス内にあるすべてのデータを取得ALL

#特定のメールUNSEEN未読メールを読み込む
term = u"alert".encode("utf-8")
mail.literal = term
type,data=mail.search("utf-8", "UNSEEN SUBJECT")

for i in data[0].split():   #data分繰り返す
 ok,x=mail.fetch(i,'RFC822')    #メールの情報を取得
 ms=email.message_from_string(x[0][1].decode('utf-8'))    #パースして取得

 #差出人を取得
 ad=email.header.decode_header(ms.get('From'))
 ms_code=ad[0][1]
 if(ms_code!=None):
  address=ad[0][0].decode(ms_code)
  address+=ad[1][0].decode(ms_code)
 else:
  address=ad[0][0]

 #本文を取得
 maintext=ms.get_payload()

 #メールの日時を取得
 time = dateutil.parser.parse(ms.get('Date')).strftime("%Y-%m-%d %H:%M")[:-1]
 time_comment = dateutil.parser.parse(ms.get('Date')).strftime("%Y-%m-%d %H:%M")

 print(time)

 #出力
#  print(sbject)
 print(address)
 print(maintext)
 
 #body文字コードを元に戻すbase64
 body_decode=(base64.b64decode(maintext).decode())
 #print(body_decode)

 def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True

 #HTMLタグを除去する関数を定義
 def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)  
    return "".join(t.strip() for t in visible_texts)

 text_change=text_from_html(body_decode)

 print(text_change)

 #Data confirm null確認
 #メールの本文がなければ、次の処理へ進まない
 if not text_change:
   print('NULL')
 else:

   mail.close()
   mail.logout()
   
   #本文から検索用語を取得
   kensaku_yougo=(re.findall('(\w+): ([-\w\s@.]+)', text_change))[0][1]
   print(kensaku_yougo)

   #検索用語を検索---------------------------------------------------------------
   # coding:utf-8
   import time
   from selenium import webdriver
   from selenium.webdriver.common.keys import Keys
   from selenium.webdriver.chrome.options import Options
   from webdriver_manager.chrome import ChromeDriverManager
   #from datetime import datetime as dt, date, timedelta
   from bs4 import BeautifulSoup
   import pyautogui
   import pandas as pd

   #headless background
   option = Options()
   #backgrand
   #option.add_argument('--headless')

   #ログイン情報を維持するための設定 
   # 参考→https://rabbitfoot.xyz/selenium-chrome-profile/

   PROFILE_PATH ="C:\\Users\\test\\AppData\\Local\\Google\\Chrome\\User Data\\" # 変更
   option.add_argument('--user-data-dir=' + PROFILE_PATH)
   option.add_argument('--profile-directory=Default')

   # ブラウザを開く。 #options=option background
   driver = webdriver.Chrome(executable_path=ChromeDriverManager().install() ,options=option)

   #Getting Default Adapter failed error message
   option.add_experimental_option('excludeSwitches', ['enable-logging'])


   #指定したURLに遷移
   URL= "https://www.google.com"

   # Googleの検索TOP画面を開く。
   driver.get(URL)

   # 2秒待機
   time.sleep(2)

   #検索用号入力
   kensaku =  driver.find_element_by_name("q")
   kensaku.send_keys(kensaku_yougo)

   #search click
   kensaku.send_keys(Keys.ENTER)   

1 件の回答 1

0

mail.close() と mail.logout() を外すとimaplib.error:が解消されました。
一件ずつメールを読み込みできるようになりました。
参考
mail.close()mail.logout()の説明について

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。