How to save email attachment using OpenPop

Pomster picture Pomster · Apr 25, 2012 · Viewed 24.6k times · Source

I have created a Web Email Application, How do I view and save attached files?

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

This works fine:

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 portion of code displays the contents of the attachment, but that's only useful if its a text file. I need to be able to save the attachment. Also the bottom section of code I have here over writes the body of my message, so if I receive an attachment I can't view my message body.

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 
        } 
    } 
}

Answer

ElectricRouge picture ElectricRouge · Feb 18, 2014

If anyone is still looking for answer this worked fine 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();
}