osparamatrix / ks-orderapi-python

47 stars 59 forks source link

Code for fetching access code from email automatically #78

Open akhil0305 opened 2 years ago

akhil0305 commented 2 years ago

Code for fetching otp from email is as below. Note : There is no problem of token expiry as you are not using Gmail API.

Before running the code enable permission for less secure apps for your google account using the below link. https://myaccount.google.com/lesssecureapps

Code:

import imaplib
import email
import html
import re

host = 'imap.gmail.com'
username = 'Your email id'
password = 'Your Password'

def get_otp():
    mail = imaplib.IMAP4_SSL(host)
    mail.login(username, password)
    mail.select("inbox")
    _, search_data = mail.search(None, 'FROM "accesscode@kotaksecurities.com"')
    my_message = []
    num = search_data[0].split()[-1]
    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']:
        email_data[header] = email_message[header]
    otp = re.search(r'\d\d\d\d', email_data['subject']).group()
    return otp
kalilinux-png commented 2 years ago

Nice

jayaprakashv2005 commented 2 years ago

After enabling 'Allow less secure App to access..', i get an below error, any suggestion

b'[ALERT] Please log in via your web browser: https://support.google.com/mail/accounts/answer/78754 (Failure)

kalilinux-png commented 2 years ago

Yes this happened with me also that's why I used Gmail API check out this issue #76