This is the desired output where the red highlighted emails are bounced emails:
I want the Python script to scrape the inbox/sent on Gmail and accordingly edit the list of emails on Excel to distinguish between bounced emails and successfully sent emails.
Here's what I have so far:
import smtplib, email, imaplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from tkinter import *
from tkinter import messagebox
import time
import pandas as pd
from datetime import datetime
import csv
def checking(user, pwd):
# need to turn on 'Allow less secure apps' in your gmail account
M = imaplib.IMAP4_SSL("imap.gmail.com")
M.login(user, pwd)
# Check Sent Mail Box
M.select('"[Gmail]/Sent Mail"')
resp, items = M.search(None,"All")
items = items[0].split()
# Obtain the emails sent out
#count = 0
inbox = {}
for item in items:
# getting email content
resp, data = M.fetch(item, "(RFC822)")
email_content = data[0][1]
msg = email.message_from_bytes(email_content)
content_list = msg.as_bytes().decode(encoding='UTF-8').split('\n')
# retrieve email address sent out
for cl in content_list:
if cl.startswith('To: '):
inbox[cl.replace("To: ",'').strip()] = 1
# print current process
#count += 1
#if count % 100 == 0:
# print(count)
fail_content = ['Delivery Status Notification (Failure)','Undeliverable:','DELIVERY FAILURE:','Returned mail:','Undelivered Mail Returned to Sender']
# check Inbox
M.select('INBOX')
resp, items = M.search(None,"All")
items = items[0].split()
#count = 1
# for each email in inbox
for item in items:
resp, data = M.fetch(item, "(RFC822)")
email_content = data[0][1]
msg = email.message_from_bytes(email_content)
# check for all possible fail content
for fc in fail_content:
if fc in msg['Subject']:
# get email content
content_list = msg.as_bytes().decode(encoding='UTF-8')
# find its sender
for eo in inbox:
if eo in content_list:
inbox[eo] = 0
M.close()
M.logout()
return inbox
So far my code is just reading the gmail but even that doesn't work. I am very new at this. So please, edit my code.