Search code examples
c#asp.netasp.net-mvcemailimap

Issues fetching sent Mail using IMAP in c#


I'm using IMAP to get the my mail from gmail. It fetches the emails from inbox fine but when it comes to sent mail, provides null values.

This the code which i'm using:

ImapClient client = new ImapClient("ExampleHost", port, ssl);
try
{
    client.Login("ExampleEmail", "ExamplePass", AuthMethod.Login);
    IEnumerable<uint> units = client.Search(SearchCondition.Seen());
    DataTable TempTaskTable = new DataTable();
    TempTaskTable.Columns.Add("FromEmail", typeof(string));
    TempTaskTable.Columns.Add("ToEmail", typeof(string));
    TempTaskTable.Columns.Add("Subject", typeof(string));
    foreach (var uid in units)
    {
        System.Net.Mail.MailMessage email = client.GetMessage(uid,true, "[Gmail]/Sent Mail");
        DataRow TempTaskRow2 = TempTaskTable.NewRow();
        TempTaskRow2["FromEmail"] = email.Sender;
        TempTaskRow2["ToEmail"] = email.From;
        TempTaskRow2["Subject"] = email.Subject;
    }

    bool result = false;
    string msg = "";
    usp_TempTasksSave(TempTaskTable, TempTaskAttachmentDatatTable, out result, out msg);
}
catch (Exception ex)
{
    string exceptionCheck = ex.Message;
}

and this is my output:

enter image description here

I have also searched on stackoverflow and so far this is the only help which i've got yet Insufficient

Any sort of help would really be appreciated.


Solution

  • I solved the issue by setting the default mailbox. In my case, the default mailbox was always INBOX due to which i was not able to fetch the sent mail. it took a single line to solve the issue. This is the code which i'm using now:

    ImapClient client = new ImapClient("ExampleHost", port, ssl);
    client.DefaultMailbox = "[Gmail]/Sent Mail";
    try
    {
        client.Login("ExampleEmail", "ExamplePass", AuthMethod.Login);
        IEnumerable<uint> units = client.Search(SearchCondition.Seen());
        DataTable TempTaskTable = new DataTable();
        TempTaskTable.Columns.Add("FromEmail", typeof(string));
        TempTaskTable.Columns.Add("ToEmail", typeof(string));
        TempTaskTable.Columns.Add("Subject", typeof(string));
        foreach (var uid in units)
        {
            System.Net.Mail.MailMessage email = client.GetMessage(uid,true, "[Gmail]/Sent Mail");
            DataRow TempTaskRow2 = TempTaskTable.NewRow();
            TempTaskRow2["FromEmail"] = email.Sender;
            TempTaskRow2["ToEmail"] = email.From;
            TempTaskRow2["Subject"] = email.Subject;
        }
    }
    catch (Exception ex)
    {
        string exceptionCheck = ex.Message;
    }
    

    You can also see all of your mailboxes using:

    List<String> mailBoxesCheck = new List<string>();
    foreach (var folder in client.ListMailboxes())
    {
       mailBoxesCheck.Add(folder);
    }