Click here to Skip to main content
15,895,709 members
Articles / Programming Languages / C#

How to Create a Spam Filter or Automatic Category Sort Algorithm with Your Mail Application

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
29 Jul 2012MIT3 min read 40.2K   1.2K   19  
This article describes automatic category filters in mail applications.
In this article, you will learn how to create a spam filter on your mail application. You will also see how to filter your mail based on whether the mail tells about a particular topic or not.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using HigLabo.Net.Mail;
using HigLabo.Net.Smtp;
using HigLabo.Net.Pop3;
using HigLabo.Net.Imap;

namespace HigLabo.Mail.SampleApplication
{
    class Program
    {
        private static String UserName = "@gmail.com";
        private static String Password = "secret";
        static void Main(string[] args)
        {
            SmtpMailSend();
            //Change method what you want to execute....
        }
        private static void SmtpMailSend()
        {
            using (var cl = new SmtpClient("smtp.gmail.com"))
            {
                cl.Port = 587;
                cl.Tls = true;
                cl.AuthenticateMode = SmtpAuthenticateMode.Auto;
                cl.UserName = UserName;
                cl.Password = Password;

                SmtpMessage mg = new SmtpMessage();
                mg.ContentEncoding = Encoding.GetEncoding("iso-8859-1");
                mg.ContentTransferEncoding = TransferEncoding.QuotedPrintable;
                mg.HeaderEncoding = Encoding.GetEncoding("iso-8859-1");
                mg.HeaderTransferEncoding = TransferEncoding.QuotedPrintable;
                mg.Date = DateTime.Now.ToUniversalTime();
                mg["Mime-Version"] = "1.0";
                mg.From = "your_name@hotmail.com";
                mg.ReplyTo = "your_name@hotmail.com";
                // set recipients
                mg.To.Add(new MailAddress("you_want_to_send_to@gmail.com"));
                // set subject if necessary
                mg.Subject = "It is a sample mail";
                // set body if necessary
                mg.BodyText = "You can send these char!äÄöÖüÜß";
                SmtpContent ct = new SmtpContent();
                mg.Contents.Add(ct);
                // send message
                SendMailResult rs = cl.SendMail(mg);
                if (rs.SendSuccessful == false)
                {
                    Console.WriteLine("Success");
                }
            }
        }
        private static void Pop3MailReceive()
        {
            MailMessage mg = null;

            using (Pop3Client cl = new Pop3Client("pop.gmail.com", 995, UserName, Password))
            {
                cl.Ssl = true;
                cl.AuthenticateMode = Pop3AuthenticateMode.Auto;
                var bl = cl.Authenticate();
                if (bl == true)
                {
                    var l = cl.ExecuteList();
                    for (int i = 0; i < l.Count; i++)
                    {
                        mg = cl.GetMessage(l[i].MailIndex);
                        foreach (var ct in mg.Contents)
                        {
                            ct.DecodeData("C:\\" + ct.FileName);
                        }
                    }
                }
            }
        }
        private static void Pop3MailReceiveUnRead()
        {
            using (Pop3Client cl = new Pop3Client("pop.gmail.com", 995, UserName, Password))
            {
                cl.Ssl = true;
                cl.AuthenticateMode = Pop3AuthenticateMode.Auto;
                var bl = cl.Authenticate();
                if (bl == true)
                {
                    var ul = cl.ExecuteUidl();
                    String path = "C:\\MailUidl.txt";
                    List<String> l = new List<String>();
                    //Get read mail index list from file
                    if (File.Exists(path) == true)
                    {
                        l.AddRange(File.ReadAllLines(path));
                    }
                    List<UidlCommandResult> unreadList = new List<UidlCommandResult>();
                    for (int i = 0; i < ul.Count; i++)
                    {
                        if (l.Contains(ul[i].Uid) == true) { continue; }
                        unreadList.Add(ul[i]);
                    }
                    //Save UIDL data to text file
                    StringBuilder sb = new StringBuilder(ul.Count * 23);
                    for (int i = 0; i < ul.Count; i++)
                    {
                        sb.AppendLine(ul[i].Uid);
                    }
                    File.WriteAllText(path, sb.ToString());
                }
            }
        }
        private static void Pop3MailDelete()
        {
            using (Pop3Client cl = new Pop3Client("pop.gmail.com", 995, UserName, Password))
            {
                cl.Ssl = true;
                //Mark as delete candidate
                cl.DeleteEMail(1, 2, 3, 4);
                //Delete from mailbox.
                cl.ExecuteQuit();
            }
        }
        private static void ImapMailReceive()
        {
            MailMessage mg = null;

            using (ImapClient cl = new ImapClient("imap.gmail.com", 993, UserName, Password))
            {
                cl.Ssl = true;
                var bl = cl.Authenticate();
                if (bl == true)
                {
                    //Select folder
                    var folder = cl.SelectFolder("[Gmail]/All Mail");
                    //Get all mail from folder
                    for (int i = 0; i < folder.MailCount; i++)
                    {
                        mg = cl.GetMessage(i + 1);
                    }
                }
            }
        }
        private static void ImapMailSearch()
        {
            MailMessage mg = null;

            using (ImapClient cl = new ImapClient("imap.gmail.com", 993, UserName, Password))
            {
                cl.Ssl = true;
                var bl = cl.Authenticate();
                if (bl == true)
                {
                    //Select folder
                    var folder = cl.SelectFolder("[Gmail]/All Mail");
                    //Search Unread
                    var list = cl.ExecuteSearch("UNSEEN UNDELETED");
                    //Get all unread mail
                    for (int i = 0; i < list.MailIndexList.Count; i++)
                    {
                        mg = cl.GetMessage(list.MailIndexList[i]);
                    }
                }
            }
        }
        private static void ImapMailDraft()
        {
            using (ImapClient cl = new ImapClient("imap.gmail.com", 993, UserName, Password))
            {
                cl.Ssl = true;
                var bl = cl.Authenticate();
                if (bl == true)
                {
                    //Add Draft
                    var smg = new SmtpMessage("xxx@gmail.com", "yyy@hotmail.com", "", "This is draft", "Hi.");
                    cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft", DateTimeOffset.Now);
                }
            }
        }
        private static void ImapMailSubscribe()
        {
            using (ImapClient cl = new ImapClient("imap.gmail.com", 993, UserName, Password))
            {
                cl.Ssl = true;
                var bl = cl.Authenticate();
                if (bl == true)
                {
                    cl.ExecuteSubscribe("[Gmail]/すべてのメール");
                    cl.ExecuteSubscribe("[Gmail]/");
                }
            }
        }
        private static void ImapMailGetSubscribeList()
        {
            using (ImapClient cl = new ImapClient("imap.gmail.com", 993, UserName, Password))
            {
                cl.Ssl = true;
                if (cl.Authenticate() == true)
                {
                    var rs = cl.ExecuteLsub("", false);
                    foreach (var line in rs.Lines)
                    {
                        var folder = new ImapFolder(line);
                    }
                }
            }
        }
        private static void ImapIdle()
        {
            using (ImapClient cl = new ImapClient("imap.gmail.com", 993, UserName, Password))
            {
                cl.Ssl = true;
                cl.ReceiveTimeout = 10 * 60 * 1000; //10 minute
                if (cl.Authenticate() == true)
                {
                    var l = cl.GetAllFolders();
                    ImapFolder r = cl.SelectFolder("INBOX");
                    using (var cm = cl.CreateImapIdleCommand()) //You must dispose ImapIdleCommand!
                    {
                        cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
                        {
                            foreach (var mg in e.MessageList)
                            {
                                String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
                                Console.WriteLine(text);
                            }
                        };
                        cl.ExecuteIdle(cm);

                        while (true)
                        {
                            var line = Console.ReadLine();
                            if (line == "done")
                            {
                                cl.ExecuteDone(cm);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
CEO TinyBetter, Inc
Japan Japan
I'm a CEO of TinyBetter, Inc in Japan.

Comments and Discussions