Download File From Email With OpenPop.Pop3

Article Overview

  • Background
    • Connect and Authenticate with Email Server
    • Get email content and file from the email
    • Download or save attached/email file
  • Pre-requisites
  • How to download or save file from email
    • Connect with Server
    • Authenticate to Server
    • Get email content of a particular one email
    • Get file from email content
    • Download file
    • Save email file on the server
  • Complete example
    • References, Model
    • Connect and authenticate with server
    • Get email content and attachment file from email
    • Get file from email content
    • Download or save attached file
    • Output
  • Summary

Background

 
There was a requirement where I had to read an email from an email box and after that, I had to download or save a file from the email. There are various libraries using which you can implement this. I have used OpenPop.NET which is a robust open-source POP3 client and MIME parser written in C#. Hence, I had to customize searched solutions in an effective and easy way.
 
This article mainly focuses on three key things:
  • Connect and Authenticate with Email Server
  • Get email content and file from the email
  • Download or save attached/email file
Here, I have kept all the implementation details along with a complete example.
 
Prerequisites

How to download a file from email

 
There are mainly six steps to perform this,
  • Connect with Server
  • Authenticate to Server
  • Get email content of a particular one email
  • Get file from email content
  • Download file
  • Save email file on the server
Now, let us see in detail.
 
Connect with Server
 
You need host (server) name, port number, etc. details to connect with the POP3 email server.
  1. Pop3Client objPOP3Client = new Pop3Client();  
  2. objPOP3Client.Connect(host, port, useSsl);  
Authenticate to Server
 
Once the server is connected you have to authenticate it using email (username) and password. This is your email box login details.
  1. objPOP3Client.Authenticate(user, password);  
Get email content of a particular one email
 
After successful authentication, you have to get email content of a particular one email using message number.
  1. MessageModel message = GetEmailContent(messageNumber, ref objPOP3Client);  
  2. objMessage = objPOP3Client.GetMessage(intMessageNumber);  
Get file from email content
 
Now, you can process email content and find all attachments. For, easy to understand I have taken first attachment file you can perform for loop to process on all files.
  1. List<MessagePart> attachment = objMessage.FindAllAttachments();  
  2. message.FileName = attachment[0].FileName.Trim();  
  3. message.Attachment = attachment;  
Download file
 
Now, you have to download attachment using byte array and write it to response using binary write.
  1. downloadFile(message);  
  2. byte[] content = attachment[0].Body;  
  3. Response.AddHeader("content-disposition""attachment; filename=" + message.FileName);  
  4. Response.BinaryWrite(content);  
Save email file on the server
 
Actually, you can also save the file on the server also, instead of download. This can be done by file write all bytes to a specific folder path.
  1. File.WriteAllBytes(Path.Combine(HttpRuntime.AppDomainAppPath, "Files/") + message.FileName, attachment[0].Body);  
Here, I have given high-level steps for our implementation. Now, let us see the complete example which will give you more clarity about these steps.
 

Complete example

 
For the complete example, I have prepared and uploaded a web site which contains all the code.
  • References, Model
  • Connect and authenticate with the server
  • Get email content
  • Get attachment file from email
  • Download or save the attached file
  • Output
References, Model
 
Include the dll reference and message model class.
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. //add references of OpenPop  
  5. using OpenPop.Mime;  
  6. using OpenPop.Pop3; 
  1. public class MessageModel  
  2. {  
  3.     public string MessageID;  
  4.     public string FromID;  
  5.     public string FromName;  
  6.     public string Subject;  
  7.     public string Body;  
  8.     public string Html;  
  9.     public string FileName;  
  10.     public List<MessagePart> Attachment;  
  11. }   
Connect and authenticate with serve
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Pop3Client objPOP3Client = new Pop3Client();  
  4.   
  5.     string host = "hostname", user = "username", password = "userpassword";  
  6.     int port = 110;  
  7.     bool useSsl = false;  
  8.   
  9.     try  
  10.     {  
  11.         objPOP3Client.Connect(host, port, useSsl);  
  12.   
  13.         objPOP3Client.Authenticate(user, password);  
  14.   
  15.         int messageNumber = 19;//  
  16.   
  17.         MessageModel message = GetEmailContent(messageNumber, ref objPOP3Client);  
  18.   
  19.         if (message != null)  
  20.         {  
  21.             downloadFile(message);  
  22.         }  
  23.     }  
  24.     catch (Exception ex)  
  25.     {  
  26.     }  
  27.     finally  
  28.     {  
  29.         objPOP3Client.Disconnect();  
  30.     }  
Get email content and get attachment file from email 
  1. public MessageModel GetEmailContent(int messageNumber, ref Pop3Client objPOP3Client)  
  2. {  
  3.     MessageModel message = new MessageModel();  
  4.   
  5.     MessagePart plainTextPart = null, HTMLTextPart = null;  
  6.   
  7.     Message objMessage = objPOP3Client.GetMessage(messageNumber);  
  8.   
  9.     message.MessageID = objMessage.Headers.MessageId == null ? "" : objMessage.Headers.MessageId.Trim();  
  10.   
  11.     message.FromID = objMessage.Headers.From.Address.Trim();  
  12.     message.FromName = objMessage.Headers.From.DisplayName.Trim();  
  13.     message.Subject = objMessage.Headers.Subject.Trim();  
  14.   
  15.     plainTextPart = objMessage.FindFirstPlainTextVersion();  
  16.     message.Body = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim());  
  17.   
  18.     HTMLTextPart = objMessage.FindFirstHtmlVersion();  
  19.     message.Html = (HTMLTextPart == null ? "" : HTMLTextPart.GetBodyAsText().Trim());  
  20.   
  21.     List<MessagePart> attachment = objMessage.FindAllAttachments();  
  22.   
  23.     if (attachment.Count > 0)  
  24.     {  
  25.         message.FileName = attachment[0].FileName.Trim();  
  26.         message.Attachment = attachment;  
  27.     }  
  28.   
  29.     return message;  
  30. }  
Download or save attached file
  1. public void downloadFile(MessageModel message)  
  2. {  
  3.     List<MessagePart> attachment = message.Attachment;  
  4.   
  5.     try  
  6.     {  
  7.         if (attachment[0] != null)  
  8.         {  
  9.             byte[] content = attachment[0].Body;  
  10.               
  11.             //[1] Save file to server path  
  12.             //File.WriteAllBytes(Path.Combine(HttpRuntime.AppDomainAppPath, "Files/") + message.FileName, attachment[0].Body);  
  13.               
  14.             //[2] Download file  
  15.             string[] stringParts = message.FileName.Split(new char[] { '.' });  
  16.             string strType = stringParts[1];  
  17.   
  18.             Response.Clear();  
  19.             Response.ClearContent();  
  20.             Response.ClearHeaders();  
  21.             Response.AddHeader("content-disposition""attachment; filename=" + message.FileName);  
  22.   
  23.             //Set the content type as file extension type  
  24.             Response.ContentType = strType;  
  25.             //attachment[0].ContentType.MediaType;  
  26.   
  27.             //Write the file content  
  28.             Response.BinaryWrite(content);  
  29.             Response.End();  
  30.         }  
  31.     }  
  32.     catch (Exception ex)  
  33.     {  
  34.     }  
Output

Summary

 
Now, I believe you will be able to download or save files from email with OpenPop.Pop3 (OpenPop.NET).


Similar Articles