How to save an email attachment using OpenPop

I created an email web application, how to view and save the attached files?

I am using OpenPop , a third party dll, I can send emails with attachments and read emails without attachments.

This works great:

Pop3Client pop3Client = (Pop3Client)Session["Pop3Client"]; // Creating newPopClient int messageNumber = int.Parse(Request.QueryString["MessageNumber"]); Message message = pop3Client.GetMessage(messageNumber); MessagePart messagePart = message.MessagePart.MessageParts[1]; lblFrom.Text = message.Headers.From.Address; // Writeing message. lblSubject.Text = message.Headers.Subject; lblBody.Text=messagePart.BodyEncoding.GetString(messagePart.Body); 

This second part of the code displays the contents of the attachment, but it is only useful if it is a text file. I need to be able to save the attachment. Also, the bottom of the code that I have here is recording the body of my message, so if I receive an attachment, I cannot view the body of the message.

 if (messagePart.IsAttachment == true) { foreach (MessagePart attachment in message.FindAllAttachments()) { if (attachment.FileName.Equals("blabla.pdf")) { // Save the raw bytes to a file File.WriteAllBytes(attachment.FileName, attachment.Body); //overwrites MessagePart.Body with attachment } } } 
+7
source share
7 answers

If someone is still looking for an answer, this worked for me.

 var client = new Pop3Client(); try { client.Connect("MailServerName", Port_Number, UseSSL); //UseSSL true or false client.Authenticate("UserID", "password"); var messageCount = client.GetMessageCount(); var Messages = new List<Message>(messageCount); for (int i = 0;i < messageCount; i++) { Message getMessage = client.GetMessage(i + 1); Messages.Add(getMessage); } foreach (Message msg in Messages) { foreach (var attachment in msg.FindAllAttachments()) { string filePath = Path.Combine(@"C:\Attachment", attachment.FileName); if(attachment.FileName.Equals("blabla.pdf")) { FileStream Stream = new FileStream(filePath, FileMode.Create); BinaryWriter BinaryStream = new BinaryWriter(Stream); BinaryStream.Write(attachment.Body); BinaryStream.Close(); } } } } catch (Exception ex) { Console.WriteLine("", ex.Message); } finally { if (client.Connected) client.Dispose(); } 
+10
source

The OpenPop.Mime.Message class has a ToMailMessage() method that converts an OpenPop message to System.Net.Mail.MailMessage , which has the Attachments property. Try to extract attachments from it.

+4
source

for future readers there is an easier way with newer versions of Pop3

 using( OpenPop.Pop3.Pop3Client client = new Pop3Client()) { client.Connect("in.mail.Your.Mailserver.com", 110, false); client.Authenticate("usernamePop3", "passwordPop3", AuthenticationMethod.UsernameAndPassword); if (client.Connected) { int messageCount = client.GetMessageCount(); List<Message> allMessages = new List<Message>(messageCount); for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } foreach (Message msg in allMessages) { var att = msg.FindAllAttachments(); foreach (var ado in att) { ado.Save(new System.IO.FileInfo(System.IO.Path.Combine("c:\\xlsx", ado.FileName))); } } } } 
+4
source

I wrote this a long time ago, but take a look at this block of code that I used to save XML attachments in email messages hosted on a POP server:

 OpenPOP.POP3.POPClient client = new POPClient("pop.yourserver.co.uk", 110, " your@email.co.uk ", "password_goes_here", AuthenticationMethod.USERPASS); if (client.Connected) { int msgCount = client.GetMessageCount(); /* Cycle through messages */ for (int x = 0; x < msgCount; x++) { OpenPOP.MIMEParser.Message msg = client.GetMessage(x, false); if (msg != null) { for (int y = 0; y < msg.AttachmentCount; y++) { Attachment attachment = (Attachment)msg.Attachments[y]; if (string.Compare(attachment.ContentType, "text/xml") == 0) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); string xml = attachment.DecodeAsText(); doc.LoadXml(xml); doc.Save(@"C:\POP3Temp\test.xml"); } } } } } 
0
source

Just in case, someone wants code for VB.NET:

 For Each emailAttachment In client.GetMessage(count).FindAllAttachments AttachmentName = emailAttachment.FileName '----// Write the file to the folder in the following format: <UniqueID> followed by two underscores followed by the <AttachmentName> Dim strmFile As New FileStream(Path.Combine("C:\Test\Attachments", EmailUniqueID & "__" & AttachmentName), FileMode.Create) Dim BinaryStream = New BinaryWriter(strmFile) BinaryStream.Write(emailAttachment.Body) BinaryStream.Close() Next 
0
source
  List<Message> lstMessages = FetchAllMessages("pop.mail-server.com", 995, true,"Your Email ID", "Your Password"); 

The above line of code retrieves a list of all messages from your email using the appropriate mail server.

For example, to get an attachment of the last (or first) email address in the list, you can write the following code snippet.

  List<MessagePart> lstAttachments = lstMessages[0].FindAllAttachments(); //Gets all the attachments associated with latest (or first) email from the list. for (int attachment = 0; attachment < lstAttachments.Count; attachment++) { FileInfo file = new FileInfo("Some File Name"); lstAttachments[attachment].Save(file); } 
0
source
  private KeyValuePair<byte[], FileInfo> parse(MessagePart part) { var _steam = new MemoryStream(); part.Save(_steam); //... var _info = new FileInfo(part.FileName); return new KeyValuePair<byte[], FileInfo>(_steam.ToArray(), _info); } //... How to use var _attachments = message .FindAllAttachments() .Select(a => parse(a)) ; 
0
source

All Articles