1

Input

This is the desired output where the red highlighted emails are bounced emails: 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.

  • Does this answer your question? [How to validate an email address using a regular expression?](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression) – Let's try Sep 14 '20 at 12:10
  • @Let'stry no. thats different. – confusedcoder Sep 14 '20 at 12:16

1 Answers1

0

i think the bounce detect works on the email end not the smtp end , there is also no such exception for that in smtplib :/, im talking from a long reasearch experience , you may try third parties apis such as : https://www.abstractapi.com/

yxxhixx
  • 29
  • 6