Downloading attachments using Imap4Client

Oct 20, 2011 at 7:09 PM

I wrote the following code to download message attachments. However, the message count is always showing as 0 even though there are attachments. Can someone help me out here if this is the right way to get the attachments? Here is the code -

 

public

void loadUnseenMessagesImap()

{

 

Imap4Client imap = new Imap4Client();

imap.Connect(imapAddress, popport);

 

imap.Login(mailTo, passWord);

 

Console.WriteLine("Getting email for user " + mailTo);

imap.Command(

"capability");

 

Mailbox inbox = imap.SelectMailbox("inbox");

 

MessageCollection mc = new MessageCollection();

 

int[] ids = inbox.Search("UNSEEN");

 

if (ids.Length > 0)

{

 

ActiveUp.Net.Mail.

Message msg_first = inbox.Fetch.MessageObject(ids[0]);

ActiveUp.Net.Mail.

Message msg = null;

 

 

for (var i = 0; i < ids.Length; i++)

{

msg = inbox.Fetch.MessageObject(ids[i]);

mc.Add(msg);

 

Console.WriteLine("msg.Attachments.Count is: " + msg.Attachments.Count);

 

if (msg.Attachments.Count > 0)

{

 

String filepath = @"C:\Documents and Settings\xxxxx\My Documents\attachments";

 

lock (filepath)

{

 

//msg.Attachments.StoreToFolder(filepath);

msg.Attachments[i].StoreToFile(filepath + msg.Attachments[i].HeaderFields[

"FileName"]);

}

 

}

 

Console.WriteLine("msg.BodyText.Text is: " + msg.BodyText.Text);

 

if (msg.BodyText.Text.Length > 0)

{

 

 

MimePart mp = msg.BodyText.ToMimePart();

 

String filepath = @"C:\Documents and Settings\xxxxx\My Documents\msgbody";

 

lock(filepath){

msg.StoreToFile(filepath);

}

}

 

}

 

 

}

}

 

Dec 30, 2011 at 2:03 PM
Edited Dec 30, 2011 at 2:04 PM

I run yo code. it actually does that coz the filename is never retrieved. use this code snippet.

replace this code:

                            //msg.Attachments.StoreToFolder(filepath);
                            //string filename = msg.Attachments[i].HeaderFields["FileName"];
                            //msg.Attachments[i].StoreToFile(filepath + filename);

with

                            var en = msg.Attachments.GetEnumerator();
                            while (en.MoveNext())
                            {
                                MimePart ob = en.Current as MimePart;
                                ob.StoreToFile(filepath + ob.Filename);
                            }