How to save email attachment using OpenPop

若如初见. 提交于 2019-11-30 07:08:31
ElectricRouge

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();
}

for future readers there is easier way with newer releases 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)));
                    }
                }
            }
           }
Stanislav Berkov

The OpenPop.Mime.Message class has ToMailMessage() method that converts OpenPop's Message to System.Net.Mail.MailMessage, which has an Attachments property. Try extracting attachments from there.

I wrote this quite a long time ago, but have a look at this block of code that I used for saving XML attachments within email messages sat 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");
                }
            }
        }
    }
}
 List<Message> lstMessages = FetchAllMessages("pop.mail-server.com", 995, true,"Your Email ID", "Your Password");

The above line of code gets the list of all the messages from your email using corresponding pop mail-server.

For example, to get the attachment of latest (or first) email in the list, you can write following piece of code.

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

Just in case someone wants the 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!