I want to retrieve the search term from the email and search it on GOOGLE.

Asked 2 years ago, Updated 2 years ago, 128 views

Loading email in Python.
Retrieves specific search terms from the body of the email.
Searching for retrieved search terms in GOOGLE

However, if there are more than one email, the following error **imaplib.error:** will occur without looping.
If I have more than one email, how should I loop it?

Error Contents

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

Example

print(kensaku_yougo)

AMERICA

JAPAN

Results you want to achieve
Example

 メール Acquire AMERICA terms from the body of the email, then search by GOOGLE
①When is finished 他 Get the terms of JAPAN from the body of another email and search by GOOGLE afterwards
未 I want to loop every time I have unread emails.

I apologize for the inconvenience, but please let me know.

Full Code

#Get email address from email body --------------------------------------------------------------------------
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 is 993, POP is 995
mail.login('example','1234')
mail.select('test')#Select Mailbox

# Load UNSEEN unread mail
# type,data=mail.search(None, 'UNSEEN')# Get all data in mailbox ALL

# Load specific mail UNSEEN unread mail
term=u "alert".encode("utf-8")
mail.literal=term
type, data=mail.search ("utf-8", "UNSEEN SUBJECT")

for i in data [0].split()—Repeat for # data minutes
 ok, x=mail.fetch(i, 'RFC822')# Get email information
 ms=email.message_from_string(x[0][1].decode('utf-8'))#parse and retrieve

 # Get sender
 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]

 # Get body
 maintext=ms.get_payload()

 # Get email date and time
 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)

 # output
#  print(sbject)
 print(address)
 print(maintext)
 
 #body Undo character code base64
 body_decode=(base64.b64decode(maintext).decode())
 # print(body_decode)

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

 # Define the function to remove HTML tags
 def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    text=soup.findAll(text=True)
    visible_texts=filter(tag_visible, text)  
    return "".join(t.strip() for invisible_texts)

 text_change=text_from_html(body_decode)

 print(text_change)

 # Check Data confirm null
 # Without the body of the email, the next process will not proceed.
 if not text_change:
   print('NULL')
 else:

   mail.close()
   mail.logout()
   
   # Retrieve search terms from body
   kensaku_yougo=(re.findall('(\w+):([-\w\s@.]+)',text_change))[0][1]
   print(kensaku_yougo)

   # Search for search terms ----------------------------------------------------------------------------
   # 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 aspd

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

   # Configuration to maintain login information 
   # Reference → https://rabbitfoot.xyz/selenium-chrome-profile/

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

   # Open your browser. # options=optionbackground
   driver=webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=option)

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


   # Transition to the specified URL
   URL="https://www.google.com"

   # Open Google's top search screen.
   driver.get (URL)

   # Wait 2 seconds
   time.sleep(2)

   # Search number input
   kensaku=driver.find_element_by_name("q")
   kensaku.send_keys(kensaku_yougo)

   #search click
   kensaku.send_keys (Keys.ENTER)   

python gmail

2022-09-29 21:29

1 Answers

Removing mail.close() and mail.logout() resolved imaplib.error:
You can now read emails one by one.
Reference
Description of mail.close()mail.logout()


2022-09-29 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.