Click here to Skip to main content
15,890,512 members
Articles / Programming Languages / C#
Tip/Trick

Read Email using PoP3 – ASP.NET, MVC5

Rate me:
Please Sign up or sign in to vote.
4.36/5 (6 votes)
10 Jul 2018CPOL2 min read 9.3K   9   1
In this tip, I am going to explain the simple steps of using POP3 in ASP.NET MVC project.

Introduction

In this article, I am going to explain how we can read email using PoP3 protocol. The sample source code can be found on github.

Note: Github project contains SMTP and POP3 sample.

POP stands for Post Office Protocol. POP3 is a recent protocol of receiving email with the help of connection medium. Protocol is like a set of basic rules, same way POP is a set of rules which sends the request to server and delivers the response to client.

Install Package

To start with project code, first we need to install OpenPop.Net from Nuget Package:

PM> Install-Package OpenPop.NET -Version 2.0.6.1120

Using the Code

Add ViewModel

Add class inside viewmodel as POPEmail.

C#
[Serializable]
    public class POPEmail
    {
        public POPEmail()
        {
            this.Attachments = new List<attachment>();
        }
        public int MessageNumber { get; set; }
        [AllowHtml]
        public string From { get; set; }
        [AllowHtml]
        public string Subject { get; set; }
        [AllowHtml]
        public string Body { get; set; }
        public DateTime DateSent { get; set; }
        [AllowHtml]
        public List<attachment> Attachments { get; set; }
    }
      [Serializable]
      public class Attachment
      {
          public string FileName { get; set; }
          public string ContentType { get; set; }
          public byte[] Content { get; set; }
      }

Controller Code

Include the package inside controller code:

C#
using OpenPop.Mime;
using OpenPop.Pop3;

Once the package is added, we can use the class Pop3Client.

C#
Pop3Client pop3Client;

Now we have the object pop3Client and we can use this to call the methods from Pop3Client class. Before reading the email, we need to make a connection with server and server can be connected using Connect() method which require ServerName, port and SSL (String, int, bool).

C#
pop3Client.Connect("ServerName", Port, SSL); //SSL is true or false

After making connect request, we need to Authenticate our request on server, for that, we use Authenticate() method which requires Email and Password (string, string)

C#
pop3Client.Authenticate("Email", "password");

Now we are connected with server, I am using count to get total number of emails in my inbox.

C#
int count = pop3Client.GetMessageCount(); //total count of email in MessageBox
var Emails = new List<POPEmail>(); //POPEmail type

Now the complete code to bind the data into Emails variable:

C#
int counter = 0;
for (int i = count; i >= 1; i--)
{
Message message = pop3Client.GetMessage(i);
POPEmail email = new POPEmail()
{
MessageNumber = i,
Subject = message.Headers.Subject,
DateSent = message.Headers.DateSent,
From = string.Format("<a href = 'mailto:{1}'>{0}</a>", 
       message.Headers.From.DisplayName, message.Headers.From.Address),
};
MessagePart body = message.FindFirstHtmlVersion();

if (body != null)
{
email.Body = body.GetBodyAsText();
}
else
{
body = message.FindFirstPlainTextVersion();
if (body != null)
{
email.Body = body.GetBodyAsText();
}
}
List<MessagePart> attachments = message.FindAllAttachments();

foreach (MessagePart attachment in attachments)
{
email.Attachments.Add(new Attachment{
FileName = attachment.FileName,
ContentType = attachment.ContentType.MediaType,
Content = attachment.Body
});
}
Emails.Add(email);
counter++;
if (counter > 2)
{
break;
}
}
var emails = Emails;
return View(emails);

View Code

By now, we have email data inside emails (POP3Email ViewModel). Next, we have to display the data on view layer. So view code will look something like this:

C#
@model IEnumerable<SendingEmailsWithWebMailInMVC.ViewModels.POPEmail>

<table class="table">     
<tr>
<th>
@Html.DisplayNameFor(model => model.MessageNumber)         
</th>         
<th>             
@Html.DisplayNameFor(model => model.From)
         </th> 
        <th>
             @Html.DisplayNameFor(model => model.Subject)
         </th>
         <th>
             @Html.DisplayNameFor(model => model.Body)
         </th>
         <th>
             @Html.DisplayNameFor(model => model.DateSent)
         </th>
         <th></th>
     </tr> @foreach (var item in Model) {
     <tr>
       <td>
             @Html.DisplayFor(modelItem => item.MessageNumber)
         </td>
         <td>
             @Html.Raw(item.From)
         </td>
         <td>
             @Html.Raw(item.Subject)
         </td>
         <td>
             @Html.Raw(item.Body)
         </td>
         <td>
             @Html.Raw(item.DateSent)
         </td>
     </tr>
 }
 </table>

Points of Interest

Wow, so you are ready with an application which can read your emails and display on your application. You can improve the UI, like truncate the EmailBody and upon clicking on email, load email on new page or popup. This was just a basic step to read email using POP3 protocol. I am not displaying attachment on table, so you can create a separate view and display the attachment from specific email.

It helped you? (Yes), then like and share (No) then share, it may help others. ;)

Cheers!

This article was originally posted at https://github.com/ritesh9835/EmailServices

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Rai Techintro
India India
A passionate .Net developer who believe in learning new things and helping others to do the same. Learning is much important like eating food for a healthy and happy life.
This is a Organisation (No members)


Comments and Discussions

 
QuestionRead Email using PoP3 – ASP.NET, MVC5 Pin
Mihail Zlatanov15-Apr-19 1:53
Mihail Zlatanov15-Apr-19 1:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.