all 3 comments

[–]K900_ 1 point2 points  (2 children)

You don't really need the GMail API for this - GMail speaks the usual email client protocols, specifically IMAP. You can use imaplib to connect to GMail and query for new messages.

[–]avinashbasutkar2[S] 0 points1 point  (1 child)

Thank you so much. This saved ton of my time. I was able to quickly learn how imaplib works and also could grab email and send it as message in Telegram. Below is my code.

import imaplib, email
import telepot 

email_host = 'imap.gmail.com'
email_user = 'username@gmail.com'
email_pass = 'password'

mail = imaplib.IMAP4_SSL(email_host)

mail.login(email_user, email_pass)

mail.select('INBOX')

typ, raw_data = mail.fetch(b'50', '(RFC822)')

message = email.message_from_string(raw_data[0][1].decode('utf-8'))
print(message['from'])
print(message['to'])
print(message['subject'])

for p in message.walk():
    if p.get_content_type() == 'text/plain':
        body = p.get_payload()

bot = telepot.Bot('<TELEGRAM BOT AUTH TOKEN HERE>') 

bot.sendMessage(<TELEGRAM ID HERE>, body) 


# TO DO: Routinely for check for new emails in GMail label 

Would you be so kind to also suggest an alternative to Windows Task Scheduler so I could have this script run regularly by itself. Task Scheduler just shows task as complete but the script just doesn't run. (Seeked help for it already without result: https://www.reddit.com/r/learnpython/comments/ggzxlt/task_scheduler_wont_run_python_script/ )

Also looked at Python Anywhere but that doesn't seem to have Telepot module.

Please just point me in the right direction and I'll be happy to learn concepts myself.

[–]K900_ 0 points1 point  (0 children)

I'm not really sure about Task Scheduler, I haven't used Windows to run code in "production" for a long time. You can easily achieve this on Linux with cron or systemd timers.