Using to Remove Spam And Keep Good Mail

 ASP.NET, Email  Comments Off on Using to Remove Spam And Keep Good Mail
Nov 142017

Recently I was cleaning up a personal mailbox I’ve kept over the years for use when a 3rd party asks for an email address and I don’t want to provide my primary one. In these situations I prefer to give an address that I don’t frequently use because I know eventually I’ll start getting targeted unsolicited mail i.e spam from them. Ordinarily when cleaning out these mailboxes I would just purge it all however on this particular occasion I needed to keep some of the legitimate mail that was mixed in with the spam.  I decided to do what any good programmer would do so I fired up some C# to surgically remove the spam.

Read Email Using POP3 With ASP.NET

When I initially checked my mailbox online I could see 3,900 unread messages waiting for me but it was obvious much of this was just marketing nonsense about 4K TVs, insurance quotes, limited time offers, and everything else you can imagine.



POP3 and IMAP are protocols used by mail clients to login to mailboxes and manage the messages contained in the mailbox.  To perform this programmatically using I decided to leverage aspNetPOP3 and aspNetMime by Dave Wanta at These components make it easy to login to a mailbox with just a few lines code.  At first I’m just going to download the message subjects into an array to identify the most repeat offenders.  After sorting the array with the subjects I write it to a file.


Looking through the file it’s easy to see how much junk there is in the mailbox. Here is just a sample:



I will manually edit the file so that it only contains the message subjects that I want to delete. In the next part of the program I log back into the mailbox and loop through each message again and compare message subject to the subjects contained in the blacklist file. If it matches then the message is marked for deletion. After the program loops through all the messages the last command is to commit the deletes.  Afterwards I will log back into the mailbox online and see how the inbox looks. If it feels like there’s still too much spam then I’ll go run the program again using a new batch of subjects.



In Summary

Sometimes it’s necessary to manually clean up the spam from a mailbox rather just purging everything. Using aspNetPOP3 and aspNetMime from it’s easy to create an program to identify and delete only the spam messages from your mailbox while keeping the good mail. Thanks for reading!


Peter Viola

Creative, customer focused, results oriented, Senior Web Systems Engineer who enjoys providing the highest level of customer service supporting complex Windows hosting solutions. MCITP, MCSA, MCTS

More Posts - Website