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.
- Pop3Client objPOP3Client = new Pop3Client();
- 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.
- 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.
- MessageModel message = GetEmailContent(messageNumber, ref objPOP3Client);
- 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.
- List<MessagePart> attachment = objMessage.FindAllAttachments();
- message.FileName = attachment[0].FileName.Trim();
- message.Attachment = attachment;
Download file
Now, you have to download attachment using byte array and write it to response using binary write.
- downloadFile(message);
- byte[] content = attachment[0].Body;
- Response.AddHeader("content-disposition", "attachment; filename=" + message.FileName);
- 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.
- 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.
- using System;
- using System.Collections.Generic;
-
-
- using OpenPop.Mime;
- using OpenPop.Pop3;
- public class MessageModel
- {
- public string MessageID;
- public string FromID;
- public string FromName;
- public string Subject;
- public string Body;
- public string Html;
- public string FileName;
- public List<MessagePart> Attachment;
- }
Connect and authenticate with serve
- protected void Page_Load(object sender, EventArgs e)
- {
- Pop3Client objPOP3Client = new Pop3Client();
-
- string host = "hostname", user = "username", password = "userpassword";
- int port = 110;
- bool useSsl = false;
-
- try
- {
- objPOP3Client.Connect(host, port, useSsl);
-
- objPOP3Client.Authenticate(user, password);
-
- int messageNumber = 19;
-
- MessageModel message = GetEmailContent(messageNumber, ref objPOP3Client);
-
- if (message != null)
- {
- downloadFile(message);
- }
- }
- catch (Exception ex)
- {
- }
- finally
- {
- objPOP3Client.Disconnect();
- }
- }
Get email content and get attachment file from email
- public MessageModel GetEmailContent(int messageNumber, ref Pop3Client objPOP3Client)
- {
- MessageModel message = new MessageModel();
-
- MessagePart plainTextPart = null, HTMLTextPart = null;
-
- Message objMessage = objPOP3Client.GetMessage(messageNumber);
-
- message.MessageID = objMessage.Headers.MessageId == null ? "" : objMessage.Headers.MessageId.Trim();
-
- message.FromID = objMessage.Headers.From.Address.Trim();
- message.FromName = objMessage.Headers.From.DisplayName.Trim();
- message.Subject = objMessage.Headers.Subject.Trim();
-
- plainTextPart = objMessage.FindFirstPlainTextVersion();
- message.Body = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim());
-
- HTMLTextPart = objMessage.FindFirstHtmlVersion();
- message.Html = (HTMLTextPart == null ? "" : HTMLTextPart.GetBodyAsText().Trim());
-
- List<MessagePart> attachment = objMessage.FindAllAttachments();
-
- if (attachment.Count > 0)
- {
- message.FileName = attachment[0].FileName.Trim();
- message.Attachment = attachment;
- }
-
- return message;
- }
Download or save attached file
- public void downloadFile(MessageModel message)
- {
- List<MessagePart> attachment = message.Attachment;
-
- try
- {
- if (attachment[0] != null)
- {
- byte[] content = attachment[0].Body;
-
-
-
-
-
- string[] stringParts = message.FileName.Split(new char[] { '.' });
- string strType = stringParts[1];
-
- Response.Clear();
- Response.ClearContent();
- Response.ClearHeaders();
- Response.AddHeader("content-disposition", "attachment; filename=" + message.FileName);
-
-
- Response.ContentType = strType;
-
-
-
- Response.BinaryWrite(content);
- Response.End();
- }
- }
- catch (Exception ex)
- {
- }
- }
Summary
Now, I believe you will be able to download or save files from email with OpenPop.Pop3 (OpenPop.NET).