CameTooFar A Nerd's False Positive

Read and Delete mails through POP3 using C#

21. June 2011 22:07 by abhilashca in C#, winform


Surprisingly, I came across a thread in asp.net forum titled “deleting mails”.

Briefly, the question was to delete mails from the mail server, via POP3. Quite some months back, I have came across an open-source library OpenPop.NET, as part of my pet project. Though, I didn’t get time to work on it at that time, but today I spend some time with the library and build a quick sample of what is asked in the above mentioned thread.

I built a simple WinForm application, which connects to the mail-server and lists the subjects of the mails. Also, allows you to delete the selected mails from the mail server.

mailcheck_deleteprompt

For storing the mail details (like Subject, message number, etc.), I created a custom class as below:

Pop3Mails.cs

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Text;
   4:  
   5: namespace POP3_MailHandling
   6: {
   7:/// <summary>
   8:/// Custom class that holds the Mail details
   9:/// </summary>
  10:public class Pop3Mails
  11:     {
  12:/// <summary>
  13:/// Message number of the mail.
  14:/// This number is used to delete the mails
  15:/// </summary>
  16:public int MessageNumber { get; set; }
  17:  
  18:/// <summary>
  19:/// Subject of the message
  20:/// </summary>
  21:public string Subject { get; set; }
  22:     }
  23: }

This class is populated with the mail details into a Generic List collection, which is then bound to a ListBox to display the details.

The code for loading messages and deleting the selected mail is as below and is commented well, so that comes to be self-explanatory.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.ComponentModel;
   4: using System.Data;
   5: using System.Drawing;
   6: using System.Text;
   7: using System.Windows.Forms;
   8:  
   9: // POP.NET Namespace
  10: using OpenPop.Mime;
  11: using OpenPop.Mime.Header;
  12: using OpenPop.Pop3;
  13: using OpenPop.Pop3.Exceptions;
  14: using OpenPop.Common.Logging;
  15:  
  16: // Used to avaoid ambiguity between 
  17: // System.Windows.Forms.Message & OpenPop.Mime.Message
  18: using Pop3Message = OpenPop.Mime.Message;
  19:  
  20: namespace POP3_MailHandling
  21: {
  22:public partial class Form1 : Form
  23:     {
  24:         Pop3Client _pop3;
  25:         Pop3Message _message;
  26:
  27:         Pop3Mails _mails;
  28:         List<Pop3Mails> _lstMails;
  29:  
  30:/// <summary>
  31:/// Gets the total Message Count
  32:/// </summary>
  33:int _totalMsgCount = 0;
  34:
  35:public Form1()
  36:         {
  37:             InitializeComponent();
  38:         }
  39:  
  40:/// <summary>
  41:/// Check Mail
  42:/// </summary>
  43:/// <param name="sender"></param>
  44:/// <param name="e"></param>
  45:private void btnCheckMail_Click(object sender, EventArgs e)
  46:         {
  47:             _pop3 = new Pop3Client();
  48: 
  49: try
  50:             {
  51: // Connect to mail-server
  52:                 _pop3.Connect(txtPop3Server.Text.Trim(), Convert.ToInt32(txtPort.Text.Trim()), chkSSL.Checked);
  53:  
  54: if (_pop3.Connected)
  55:                 {
  56: // Authenticate
  57:                     _pop3.Authenticate(txtUsername.Text.Trim(), txtPassword.Text.Trim());
  58:  
  59: // Get Total Count
  60:                     _totalMsgCount = _pop3.GetMessageCount();
  61:                     lblTotalMsg.Text = _totalMsgCount.ToString();
  62:  
  63: // Check for Mails
  64: if (_totalMsgCount == 0)
  65:                     {
  66:                         MessageBox.Show("Mailbox is empty");
  67: return;
  68:                     }
  69: 
  70: // Clear Listbox
  71:                     lstboxMails.Items.Clear();
  72:  
  73:                     _lstMails = new List<Pop3Mails>();
  74: 
  75: // Loop through Mails
  76: for (int i = _totalMsgCount; i <= _totalMsgCount; i--)
  77:                     {
  78: if (i == 0)
  79: break;
  80:  
  81: // Allow to handle other messages in the message queue
  82: // Thus preventing the application to show 'Not Responding'
  83:                         Application.DoEvents();
  84:  
  85: // Mail
  86:                         _message = _pop3.GetMessage(i);
  87:  
  88: // Get mail details
  89:                         _mails = new Pop3Mails();
  90:                         _mails.MessageNumber = i;
  91:                         _mails.Subject = _message.Headers.Subject;
  92:  
  93:                         _lstMails.Add(_mails);
  94:                     }
  95:  
  96: // Bind Mail details
  97:                     lstboxMails.DisplayMember = "Subject";
  98:                     lstboxMails.ValueMember = "MessageNumber";
  99:                     lstboxMails.DataSource = _lstMails;
 100:  
 101:                     MessageBox.Show("Mail fetching Completed!");
 102:                 }
 103:             }
 104: catch (Exception exp)
 105:             {
 106:                 MessageBox.Show("Oops! An error occured: " + exp.Message);
 107:             }
 108:         }
 109:  
 110:/// <summary>
 111:/// Delete Mail
 112:/// </summary>
 113:/// <param name="sender"></param>
 114:/// <param name="e"></param>
 115:private void btnDeleteMail_Click(object sender, EventArgs e)
 116:         {
 117:             DialogResult dlgResult = MessageBox.Show("Do you want to delete this message?", "Confirmation", MessageBoxButtons.YesNo);
 118:  
 119: if (dlgResult == System.Windows.Forms.DialogResult.No)
 120:             {
 121: return;
 122:             }
 123:  
 124: // Get the selected mail item
 125:             Pop3Mails _mailSel = lstboxMails.SelectedItem as Pop3Mails;
 126:  
 127: if (_mailSel != null)
 128:             {
 129: // Set the message count to be deleted
 130:                 _pop3.DeleteMessage(_mailSel.MessageNumber);
 131:  
 132: // Calling disconnected deletes the mail from server
 133:                 _pop3.Disconnect();
 134:             }
 135: else
 136:             {
 137:                 MessageBox.Show("Please select a mail to delete");
 138:             }
 139:         }
 140:     }
 141: }

Last but not the least, the documentation of POP.NET is pretty good and neat; and is easily to use.

Download Sample

Hope this helped.

Thanks!

Update: I mentioned Pop.NET instead of OpenPop.net and linked to an wrong project (Pop.NET) in sourceforge. Thanks for pointing out the mistake. The links are updated now.

Note: This post is composed with limited time period. Hence, may be revised later for adding more clarity.