This project is read-only.

Fetch all messages from inbox

Topics: Feature Requests, Help requests, Issues
Jun 17, 2014 at 7:40 PM
hi pavel, i want to fetch all messages from inbox without any specific search, i'm sahring what i have done so far please guide me please.

public async Task getMessage()
    {

        using (var client = new ImapClient("imap.gmail.com", true))
        {

            // Download only the headers we need
            client.Behavior.RequestedHeaders = new[] 
            {
                MessageHeader.ContentType,
                MessageHeader.Date,
                MessageHeader.From,           
                MessageHeader.MessageId
            };

            // Do not examine folders, it will gain us performance
            client.Behavior.ExamineFolders = false;

            // Download body, attachments, flags and headers
            client.Behavior.MessageFetchMode = MessageFetchMode.Body | MessageFetchMode.Attachments | MessageFetchMode.Flags | MessageFetchMode.Headers;

            // Connecting
            if (client.Connect())
            {
                // Sign in
                if (client.Login("abcd@gmail.com", "abcdef"))
                {

                    var excludeLabels = new string[] { "Processed", "Research", "MANUAL", "Failed", "Success", "Duplicate" };


                    // Building the search query
                    var query = string.Format("X-GM-RAW \"{0} -({1})\"",
                                                    string.Join(" OR ", "ALL"),
                                                    string.Join(" OR ", excludeLabels.Select(label => "(label:" + label + ")")));

                    var messages = client.Folders.Inbox.Search(query, MessageFetchMode.ClientDefault, 1000);

                    foreach (var msg in messages)
                    {
                        // Mark the message as seen
                        msg.Seen = true;
                        string plainTextBody = msg.Body.HasText ? msg.Body.Text : "";
                        string htmlBody = msg.Body.HasHtml ? msg.Body.Html : "";

                        var time = DateTime.SpecifyKind(msg.Date.HasValue ? msg.Date.Value : DateTime.Now, DateTimeKind.Utc);

                        if (msg.Attachments.Count() > 0)
                        {
                            foreach (var file in msg.Attachments)
                            {
                                var folder = Server.MapPath("~/Data/InboxAttachments");
                                if (!Directory.Exists(folder))
                                {
                                    Directory.CreateDirectory(folder);
                                }
                                string guid = Guid.NewGuid().ToString();
                                string webPath = null;
                                msg.Download(MessageFetchMode.Full);
                                int posOfDot = file.FileName.LastIndexOf(".");
                                string fName = Guid.NewGuid().ToString() + file.FileName.Substring(posOfDot);
                                webPath = "~/Data/InboxAttachments/" + fName;
                                file.Save(Server.MapPath("~/Data/InboxAttachments"), fName);

                                db.MailSystems.AddOrUpdate(c => c.MESSAGEID, new MailSystem
                                {
                                    Message = htmlBody,
                                    Date = time,
                                    Attachment = webPath,
                                    EmailType = "IMAP",
                                    Subject = string.IsNullOrEmpty(msg.Subject) ? "No Subject" : msg.Subject,
                                    Sender = msg.Sender.Address,
                                    MESSAGEID = msg.MessageId
                                });
                            }
                        }
                        else
                        {                                
                            db.MailSystems.AddOrUpdate(c => c.MESSAGEID, new MailSystem
                            {
                                Message = htmlBody,
                                Date = time,
                                //   Attachment = webPath,
                                EmailType = "IMAP",
                                Subject = string.IsNullOrEmpty(msg.Subject) ? "No Subject" : msg.Subject,
                                Sender = msg.Sender.Address,
                                MESSAGEID = msg.MessageId
                            });
                        }

                        await db.SaveChangesAsync();                            
                    }
                }
            }
        }
    }
i'm getting error on this line "db.MailSystems.AddOrUpdate(c => c.MESSAGEID, new MailSystem"
error is "object reference not set to an instance of an object", i think it is not downloading messages becasue when i insert certain email query it will fetch the messages normally but i want all my inbox messages, please guide me
Coordinator
Jun 18, 2014 at 10:23 AM
Edited Jun 18, 2014 at 10:24 AM
Hi,

to fetch all messages in a folder at a time you have two options:

Using Folder.Search
var messages = client.Folders.Inbox.Search();
foreach (var msg in messages)
{
     // ...
}
Directly through Folder.Messages
client.Folders.Inbox.Messages.Download();
foreach (var msg in client.Folders.Inbox.Messages)
{
     // ...
}
About the NullReferenceException you mentioned

I'm pretty sure that it occurs when you access msg.Sender.Address, as the Sender header is not being fetched due to the configuration you provided when creating the client. To fix it, simply use msg.From.Address:
db.MailSystems.AddOrUpdate(c => c.MESSAGEID, new MailSystem
{
      // .. your code
      Sender = msg.From.Address,
      // .. your code
});
Greets,

Pavel