Automate your computer- remove emails
Tags: python, automation, automate, email
Published: 2019-06-30 05:17:24

So I encountered a really annoying problem at my work.
We have support auto-emails and they send me to much emails.

What most people would do in this situation? make a rule to put it in a different folder.
So now I have 300,000+ emails their and I can not enter to the folder, the outlook is crushing... what should we do?

###Lets write a script that delete our emails.

For that we will use imaplib library.
```python
import imaplib
```

We also will use datetime so:
```python
import datetime
```

Next we need a new class..

```python
class EmailCleaner:
    def deleteEmail(self):
        imap_host = 'imap-mail.outlook.com' # for gmail please use: 'imap.gmail.com'
        mail = imaplib.IMAP4_SSL(imap_host)
        mail.login('your email', 'your password')
```


We created a new class called "EmailCleaner", inside we create new method called "deleteEmail".
The next 3 lines define the host (outlook in my example), open SSL connection and preform login to your email.

After we logged-in lets select the required folder and start running on it.
For that we need to get the folder name and how many days (my deafult is 50) we want to go throw.


```python
class EmailCleaner:
    def deleteEmail(self, folderName, daysBack = 50):
        imap_host = 'imap-mail.outlook.com'
        mail = imaplib.IMAP4_SSL(imap_host) 
        mail.login('your email', 'your password')
        mail.select(mailbox=folderName, readonly=False)

        for i in range(0, daysBack):
            date = (datetime.date.today() - datetime.timedelta(i)).strftime("%d-%b-%Y")
            result, data = mail.search(None, '(SENTSINCE {0})'.format(date))
```

We just selected the requested folder via mail.select and put readonly=false cause we want to remove it.

By default we can not get all the email, but only in batches (~1000), so I created a loop on the days and it will remove the emails depend on the day.
Then I searched for the requested emails by date- "SENTSINCE".
**For other queries you can read here: [RFC](https://tools.ietf.org/html/rfc1730.html)**

```python
 for num in data[0].split():
     mail.store(num, '+FLAGS', r'(\Deleted)')
     print(f'adding email {num} to remove list...')
```

I created nested loop, and mark every email with delete flag.

So we did login, selected a folder and run in for loop on that folder, get the emails by date and mark them with deleted flag, now it's time for **delete the emails**.

For delete the emails we will use this:
```python
mail.expunge()
```

Let's check out all the code (I added some prints)...

```python
def deleteEmail(self, folderName, daysBack = 50):
	mail = imaplib.IMAP4_SSL(imap_host)
        mail.login('your email', 'your password')

	print("Login success")
	mail.select(mailbox=folderName, readonly=False)

	for i in range(0, daysBack):
		date = (datetime.date.today() - datetime.timedelta(i)).strftime("%d-%b-%Y")
		result, data = mail.search(None, '(SENTSINCE {0})'.format(date))

		for num in data[0].split():
			mail.store(num, '+FLAGS', r'(\Deleted)') #change flag to delete
			print(f'adding email {num} to remove list...')
		mail.expunge() # delete the emails
		print(f'Emails back from day: {i} removed.')
        # close connection and logout
	mail.close()
	mail.logout()
```

It's almost ready! now lets add try\catch now handle exceptions.
```python
    def deleteEmail(self, folderName, daysBack = 50):
        try:
            mail = imaplib.IMAP4_SSL(imap_host)
            mail.login('your email', 'your password')

            print("Login success")
            mail.select(mailbox=folderName, readonly=False)

            for i in range(0, daysBack):
                date = (datetime.date.today() - datetime.timedelta(i)).strftime("%d-%b-%Y")
                result, data = mail.search(None, '(SENTSINCE {0})'.format(date))

                for num in data[0].split():
                    mail.store(num, '+FLAGS', r'(\Deleted)')
                    print(f'adding email {num} to remove list...')
                mail.expunge()
                print(f'Emails back from day: {i} removed.')
            mail.close()
            mail.logout()
        except Exception as e:
            raise Exception(f'Unable to delete emails, e.')
```

If you want to start it via the console, you can add console interface with Fire.
You can out my post how to implement that: [Automatically generate command line interfaces](https://dev.to/roybs2/automatically-generate-command-line-interfaces-2b3e)


**Enjoy :) **