Question

I am developing a console application,where i want to download the attachment from mails coming to the Mail(only one account).I am able to download the attachment,if the attachment is attached to the mail directly,i am using OpenPop library.Below is the code to download/save the attachment.

Pop3Client client = new Pop3Client();    
client.Connect("MailServer", PortNumber,UseSSL,receiveTimeout, sendTimeout,certificateValidator);
client.Authenticate(username, password);
List<Message> _messages = new List<Message>();
int messageCount = client.GetMessageCount();             
for (int i = messageCount; i > 0; i--)
{
    _messages .Add(client.GetMessage(i));                    
}
string _path = @"D:\Attachments";
foreach (Message message in _messages)
{                  
    foreach (MessagePart attachment in message.FindAllAttachments())
    {
        string filePath = Path.Combine(_path, attachment.FileName);
        if (Path.GetExtension(filePath) == ".xlsx")
        {
            FileStream Stream = new FileStream(filePath, FileMode.Create);
            BinaryWriter BinaryStream = new BinaryWriter(Stream);
            BinaryStream.Write(attachment.Body);
            Stream.Close();
            BinaryStream.Close();                                                
         }
     }
 }

But i am getting mails like,each mail is a collection of Messages and each Message has one attachment. For Example: mail from abc@example.com,this mail contains list of messages,each message has one attachment,how to get this attachment.? i tried var mailbody = message.MessagePart.MessageParts.FirstOrDefault(); its not working.

No correct solution

OTHER TIPS

Check this site. It has complete code explaining how to fetch and read email messages with attachments. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top