How to Read a Mail in Gmail Fromk a Python Code

How to Read Emails in Python?

To read emails from an email server, we use the Internet Message Access Protocol (IMAP) protocol. Although you tin can visit the email service provider website like gmail.com and wait upwards the emails present in your Inbox, it would be cool to write a Python script that tin read or fetch emails from your Inbox. And here, in this Python tutorial, we volition walk yous through the steps y'all need to follow to fetch emails from your Gmail Inbox.

How to Read Emails in Python?

For this tutorial, nosotros will be fetching the mails preset in a Gmail inbox, and to be more specific, we volition be fetching only those emails that are sent from a specific electronic mail accost. When we try to access our Gmail account with any programming language or third-party package, nosotros receive the following error.

imaplib.IMAP4.error: b'[Alarm] Application-specific password required

Y'all become this error considering Gmail blocks the request of third-party packages or applications if 2 Step Verification is active for your account. You can simply solve this mistake past deactivating the 2 Pace verification, but we would not propose that.

Instead, you can apply the Gmail App Password and generate an alternative app password for your Gmail account. With this, you do non have to deactivate 2 Step Verification and you can access your Gmail account with Python or any other tertiary-party package. This Python tutorial is divided into three sections:

  1. In Department ane, you will learn how to generate or set up a Gmail App countersign.
  2. Department 2 will particular the libraries required to write the Python program to read emails.
  3. InSection 3, we will walk you lot through the Python program to read the emails in your Gmail account.

If you already know how to gear up or generate a Gmail App password or you are using a different Email service, y'all can skip sections 1 and 2 and go directly to Section iii for the Python program. Otherwise, beginning from Section ane.

Section i: Set App Password for Gmail

Again, we are generating the App Password considering Gmail does not allow united states to log in to the Gmail account with third-party packages if the 2 Stride Verification feature is on. The generated App Password volition thus, aid usa to log in to our Gmail business relationship with an alternative generated password.

Step one: Go to the Google My Account Settings, and you will see a screen like as shown beneath:

Step 2: Navigate toSecurity>>>App passwords.

Vamware

When y'all click on the App passwords, Google might ask you to enter your countersign. Practise it to keep.

Step iii: Select App toOther(Custom Proper name) choice and requite a Custom proper name to your app. We have given our App name "ReadEmail." After specifying the proper noun, hit the GENERATE button.

Step 4:When y'all hit on theGENERATE button, a small window will prompt containing a 16-character countersign. Copy the password and practise not share it with anyone.

Vamware

At present you have successfully generated the App Password. Exercise not forget to copy it on your Notepad or clipboard of your Python IDE.

Section 2: Importing the Python imaplib Library

The imaplib library is a standard Python library for handling IMAP protocols. As it is a part of Python Standard Libraries, you do not have to worry about installing information technology because it comes preinstalled with Python. We will be using this library to connect with the email service provider server (Gmail in our case) and log in to the server with the login credentials.

Python e-mail Library

The Python email library is besides a standard Python library that is used to handle Multipurpose Cyberspace Mail Extensions (MIME) standards. A mail contains multiple pieces of information, and so we volition be using this library to extract information from an email, such as subject, engagement, from, and bulletin.

We are done with sections 1 and 2. Thus, it's time to write the code to read emails in Python. Open your best Python IDE or text editor and follow along.

Department 3: How to Read Emails in Python?

Let's start with importing imaplib and email modules and also declare the credentials and host provider server.

#modules import imaplib import email  #credentials username ="codehundred100@gmail.com"  #generated app countersign app_password= "aqwertyuiopasdfa"  # https://www.systoolsgroup.com/imap/ gmail_host= 'imap.gmail.com'

In this tutorial, nosotros will exist reading a Gmail Inbox. Thus, our host server is 'imap.gmail.com', but if you lot are trying to access a different email provider, such equally Hotmail or Outlook, click here to know the server name for your host. Next, allow's set a connection to the Gmail host server with the help of imaplib. IMAP4SSL() library, and log in to the server with the login() method credentials.

#ready connexion post = imaplib.IMAP4_SSL(gmail_host)  #login post.login(username, app_password)

Now we are successfully logged in to the Gmail server with our Gmail account. Side by side, let's select the "INBOX" to read the messages. To select the Inbox, we will use the mail.select()method.

#select inbox mail.select("INBOX")

Here, nosotros are reading messages from the Inbox, and that's why we specify "INBOX" as an argument to the select() function. Y'all tin also read letters from other mailboxes nowadays on your mail server. To list out all available mailboxes, you can use the post.list()method.

Our Inbox is full of emails, and so for this tutorial, we volition just exist reading mail from " noreply@kaggle.com."  To specify the mails that nosotros will read, nosotros will employ the postal service.search() method.

#select specific mails _, selected_mails = mail.search(None, '(FROM "noreply@kaggle.com")')  #total number of mails from specific user impress("Total Messages from noreply@kaggle.com:" , len(selected_mails[0].split()))

If you wish, you tin can also fetch the UNSEEN messages using the mail.search(None, 'UNSEEN') statement. The post.search() method returns a list of single binary data representing emails ID in bytes. Now we volition split that single binary data and loop through every electronic mail ID and access its content using the e-mail module.

for num in selected_mails[0].split():     _, data = mail.fetch(num , '(RFC822)')     _, bytes_data = information[0]      #convert the byte data to message     email_message = e-mail.message_from_bytes(bytes_data)     print("\n===========================================")      #admission data     print("Subject field: ",email_message["subject"])     print("To:", email_message["to"])     print("From: ",email_message["from"])     print("Appointment: ",email_message["date"])     for part in email_message.walk():         if function.get_content_type()=="text/apparently" or part.get_content_type()=="text/html":             message = part.get_payload(decode=True)             print("Bulletin: \n", message.decode())             print("==========================================\north")             break        

Now it'southward fourth dimension to put all the code together and execute information technology.

#Python programme to read emails from Gmail.

#modules import imaplib import email  #credentials username ="codehundred100@gmail.com"  #generated app password app_password= "aqwertyuiopasdfa"  # https://www.systoolsgroup.com/imap/ gmail_host= 'imap.gmail.com'  #prepare connection mail = imaplib.IMAP4_SSL(gmail_host)  #login mail service.login(username, app_password)  #select inbox mail.select("INBOX")  #select specific mails _, selected_mails = post.search(None, '(FROM "noreply@kaggle.com")')  #total number of mails from specific user print("Total Messages from noreply@kaggle.com:" , len(selected_mails[0].split()))  for num in selected_mails[0].carve up():     _, data = mail.fetch(num , '(RFC822)')     _, bytes_data = information[0]      #convert the byte data to bulletin     email_message = e-mail.message_from_bytes(bytes_data)     print("\n===========================================")      #access data     print("Subject: ",email_message["subject area"])     print("To:", email_message["to"])     print("From: ",email_message["from"])     print("Engagement: ",email_message["date"])     for part in email_message.walk():         if function.get_content_type()=="text/manifestly" or part.get_content_type()=="text/html":             message = office.get_payload(decode=True)             print("Message: \n", message.decode())             impress("==========================================\n")             break        

Output

Total Letters from noreply@kaggle.com: 7  =========================================== Discipline:  Competition Recap: Google Inquiry Football Simulation To: codehundred100@gmail.com From:  Kaggle <noreply@kaggle.com> Date:  Tue, 12 Jan 2021 xv:55:36 -0800 Message:    ==========================================  =========================================== Subject field:  Competition Recap: NFL Impact Detection To: codehundred100@gmail.com From:  Kaggle <noreply@kaggle.com> Date:  Fri, fifteen January 2021 09:52:27 -0800 Bulletin:    ==========================================  =========================================== Subject field:  Competition Recap: Riiid! Reply Definiteness Prediction To: codehundred100@gmail.com From:  Kaggle <noreply@kaggle.com> Date:  Tue, 19 Jan 2021 13:fourteen:53 -0800 Message:    ==========================================        

Conclusion

In this Python tutorial, you learned "How to Read Emails in Python?". Using Python we read the emails from a Gmail account, without deactivating the two step verification. We used Google App Password to connect our Python script to the Gmail account, then our Python program could read the email from the inbox. You lot do not need to practice it if you lot are using a different email provider or server. There, you tin log in to your business relationship only with your email id and countersign with the Python program.

We would urge you to go through the official documentation of the Python imaplib and electronic mail modules to know more than virtually these 2 libraries. All the all-time!

People are besides reading:

  • Pass Keyword in Python
  • Python Lambda Function
  • Function Arguments in Python
  • Python Recursion
  • Keep & Break Keywords in Python
  • Python Custom Exception
  • Object-oriented Programming in Python
  • Python Course and Objects
  • NumPy Matrix Multiplication
  • Top Online Python Courses & Certificates

boothwheirlemse1976.blogspot.com

Source: https://www.techgeekbuzz.com/how-to-read-emails-in-python/

0 Response to "How to Read a Mail in Gmail Fromk a Python Code"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel