How to read emails from gmail?

2024/10/8 19:44:27

I am trying to connect my gmail to python, but show me this error:

I already checked my password, any idea what can be?

b'[AUTHENTICATIONFAILED] Invalid credentials (Failure)'
Traceback (most recent call last):File "/Users/myuser/Documents/migrations/untitled3.py", line 29, in read_email_from_gmailmail.login(FROM_EMAIL,FROM_PWD)File "/Users/myuser/opt/anaconda3/lib/python3.9/imaplib.py", line 612, in loginraise self.error(dat[-1])
imaplib.IMAP4.error: b'[AUTHENTICATIONFAILED] Invalid credentials (Failure)'

Here my code: Also i want to know which port I can use?

import smtplib
import time
import imaplib
import email
import traceback ORG_EMAIL = "@gmail.com" 
FROM_EMAIL = "myemail" + ORG_EMAIL 
FROM_PWD = "mypassword" 
SMTP_SERVER = "smtp.gmail.com" 
SMTP_PORT = ??def read_email_from_gmail():try:mail = imaplib.IMAP4_SSL(SMTP_SERVER)mail.login(FROM_EMAIL,FROM_PWD)mail.select('inbox')data = mail.search(None, 'ALL')mail_ids = data[1]id_list = mail_ids[0].split()   first_email_id = int(id_list[0])latest_email_id = int(id_list[-1])for i in range(latest_email_id,first_email_id, -1):data = mail.fetch(str(i), '(RFC822)' )for response_part in data:arr = response_part[0]if isinstance(arr, tuple):msg = email.message_from_string(str(arr[1],'utf-8'))email_subject = msg['subject']email_from = msg['from']print('From : ' + email_from + '\n')print('Subject : ' + email_subject + '\n')except Exception as e:traceback.print_exc() print(str(e))read_email_from_gmail()

My main goal is be able to get the CSV file from each email, but for now I just want to read messages.

Answer

Best way to read email is using GMAIL API. Google has stopped accessing gmail account using username and password via any outside app from 30 the May 2022. So this is how you read gmail from python.

What this app does:

  • Read gmail message (Unread)
  • Make the message as Read after reading the message
import os.path
import base64
import json
import re
import time
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
import logging
import requestsSCOPES = ['https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.modify']def readEmails():"""Shows basic usage of the Gmail API.Lists the user's Gmail labels."""creds = None# The file token.json stores the user's access and refresh tokens, and is# created automatically when the authorization flow completes for the first# time.if os.path.exists('token.json'):creds = Credentials.from_authorized_user_file('token.json', SCOPES)# If there are no (valid) credentials available, let the user log in.if not creds or not creds.valid:if creds and creds.expired and creds.refresh_token:creds.refresh(Request())else:flow = InstalledAppFlow.from_client_secrets_file(               # your creds file here. Please create json file as here https://cloud.google.com/docs/authentication/getting-started'my_cred_file.json', SCOPES)creds = flow.run_local_server(port=0)# Save the credentials for the next runwith open('token.json', 'w') as token:token.write(creds.to_json())try:# Call the Gmail APIservice = build('gmail', 'v1', credentials=creds)results = service.users().messages().list(userId='me', labelIds=['INBOX'], q="is:unread").execute()messages = results.get('messages',[]);if not messages:print('No new messages.')else:message_count = 0for message in messages:msg = service.users().messages().get(userId='me', id=message['id']).execute()                email_data = msg['payload']['headers']for values in email_data:name = values['name']if name == 'From':from_name= values['value']                for part in msg['payload']['parts']:try:data = part['body']["data"]byte_code = base64.urlsafe_b64decode(data)text = byte_code.decode("utf-8")print ("This is the message: "+ str(text))# mark the message as read (optional)msg  = service.users().messages().modify(userId='me', id=message['id'], body={'removeLabelIds': ['UNREAD']}).execute()                                                       except BaseException as error:pass                            except Exception as error:print(f'An error occurred: {error}')

You need to create credential file in Google account How to create credential file here https://cloud.google.com/docs/authentication/getting-started

https://en.xdnf.cn/q/70100.html

Related Q&A

Python multiprocessing returning AttributeError when following documentation code [duplicate]

This question already has answers here:python multiprocessing in Jupyter on Windows: AttributeError: Cant get attribute "abc"(4 answers)Closed 4 years ago.I decided to try and get into the mu…

Python - How can I find if an item exists in multidimensional array?

Ive tried a few approaches, none of which seem to work for me. board = [[0,0,0,0],[0,0,0,0]]if not 0 in board:# the board is "full"I then tried:if not 0 in board[0] or not 0 in board[1]:# the…

Convert Geo json with nested lists to pandas dataframe

Ive a massive geo json in this form:{features: [{properties: {MARKET: Albany,geometry: {coordinates: [[[-74.264948, 42.419877, 0],[-74.262041, 42.425856, 0],[-74.261175, 42.427631, 0],[-74.260384, 42.4…

Pymongo - ValueError: NaTType does not support utcoffset when using insert_many

I am trying to incrementally copy documents from one database to another. Some fields contain date time values in the following format:2016-09-22 00:00:00while others are in this format:2016-09-27 09:0…

python numpy argmax to max in multidimensional array

I have the following code:import numpy as np sample = np.random.random((10,10,3)) argmax_indices = np.argmax(sample, axis=2)i.e. I take the argmax along axis=2 and it gives me a (10,10) matrix. Now, I …

Can Keras model.predict return a dictionary?

The documentation https://keras.io/models/model/#predict says that model.predict returns Numpy array(s) of predictions. In the Keras API, is there is a way to distinguishing which of these arrays are…

Flask OIDC: oauth2client.client.FlowExchangeError

The Problem: The library flask-oidc includes the scope parameter into the authorization-code/access-token exchange request, which unsurprisingly throws the following error:oauth2client.client.FlowExcha…

Cumulative count at a group level Python

I have a pandas dataframe like this : df = pd.DataFrame([[A, 1234, 20120201],[A, 1134, 20120201],[A, 1011, 20120201],[A, 1123, 20121004],[A, 1111, 20121004],[A, 1224, 20121105],[B, 1156, 20120403],[B, …

Easiest ways to generate graphs from Python? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Stripping python namespace attributes from an lxml.objectify.ObjectifiedElement [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:When using lxml, can the XML be rendered without namespace attributes? How can I strip the python attributes from an lxml…