0
votes

Here I have written code for Gmail API to fetch mail with date filter
I am able to fetch MessageId and ThreadId using the First API. On the basis of MessageId, I put that messageId parameter in a List object and I have sent this parameter in foreach loop from List to the next API to fetch email body on basis of messageID. But the process is very slow for fetching messages from Gmail

public async Task<ActionResult> DisplayEmailWithFilter (string fromDate, string toDate) {

    Message messageObj = new Message ();
    Example exampleObj = new Example ();
    List<GmailMessage> gmailMessagesList = new List<GmailMessage> ();
    GmailMessage gmailMessage = new GmailMessage ();
    var responseData = "";
    //dateFilter string parameter Created with Date Values 
    string dateFilter = "in:Inbox after:" + fromDate + " before:" + toDate;

    try {
        // calling Gmail API to get MessageID Details by Date Filter
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue (scheme: "Bearer",
            parameter : Session["Token"].ToString ());
        HttpResponseMessage responseMessage = await client.GetAsync ("https://www.googleapis.com/gmail/v1/users/me/messages?q=" + dateFilter);
        if (responseMessage.IsSuccessStatusCode) {
            var data = responseMessage.Content;
        }

        try {
            responseData = responseMessage.Content.ReadAsStringAsync ().Result;
            //This Json Data Converted into List Object
            var msgList = JsonConvert.DeserializeObject<Root1> (responseData);
            //loop for Fetching EmailMessageData by MessageID
            if (msgList.resultSizeEstimate != 0) {

                foreach (var msgItem in msgList.messages) {
                    messageObj.id = msgItem.id;

                    //Calling API with MessageID Parameter to fetch Respective Message Data 
                    HttpResponseMessage responseMessageList = await client.GetAsync ("https://www.googleapis.com/gmail/v1/users/userId/messages/id?id=" + messageObj.id.ToString () + "&userId=me&format=full");
                    if (responseMessageList.IsSuccessStatusCode) {
                        var dataNew = responseMessageList.Content;
                        var responseDataNew = responseMessageList.Content.ReadAsStringAsync ().Result;
                        //Converting json string in Object
                        exampleObj = JsonConvert.DeserializeObject<Example> (responseDataNew);

                        gmailMessage.Body = exampleObj.snippet;
                        //fetching Header Values comparing with string to get Data
                        for (int i = 1; i < exampleObj.payload.headers.Count; i++) {
                            if (exampleObj.payload.headers[i].name.ToString () == "Date") {
                                gmailMessage.RecievedDate = exampleObj.payload.headers[i].value;
                            }
                            if (exampleObj.payload.headers[i].name.ToString () == "Subject") {
                                gmailMessage.Subject = exampleObj.payload.headers[i].value;
                            }
                            if (exampleObj.payload.headers[i].name.ToString () == "Message-ID") {
                                gmailMessage.SenderEmailID = exampleObj.payload.headers[i].value;
                            }
                            if (exampleObj.payload.headers[i].name.ToString () == "From") {
                                gmailMessage.SenderName = exampleObj.payload.headers[i].value;
                            }
                        }

                        //Adding This Object Values in GmailMessgage List Object
                        gmailMessagesList.Add (
                            new GmailMessage {
                                Body = exampleObj.snippet,
                                    SenderEmailID = gmailMessage.SenderEmailID,
                                    RecievedDate = gmailMessage.RecievedDate,
                                    SenderName = gmailMessage.SenderName,
                                    Subject = gmailMessage.Subject,
                            });
                    }

                }
            }
        } catch (Exception e) {

            string errorMgs = e.Message.ToString ();
            throw;
        }
    } catch (Exception e) {

        string errorMgs = e.Message.ToString ();
        throw;
    }

    return View (gmailMessagesList);

}

I can fetch Gmail email datewise but it took so much time to fetch. how can I improve my code and performance faster?

1
The coding taking "so much time" could be completely normal an relative to your expectations. In those cases please try to provide factual information, how many seconds, how does it compare to doing this directly into the UI? Also what is the reason for not using the C# library?Raserhin
@Raserhin I m unable to understand C# library example from Google shown in guide reference and how to add Credential.json file how it works so I wrote this type of code. As you asked Its taking 1 Sec for execution API but I m using Foreach loop to fetch Email Data by MessageId so API calling multiple Times with different MessageID. Can you suggest me any other option to fetch datewise Messages from InboxRohit Satpute
I think there is not much you can do in terms of querying the individual message, is this really affecting your workflow? Do you have issue because this performance issue?Raserhin
@Raserhin Yes this is affecting my workflow. I m calling the second API in loop with msgID parameter to fetch selective Email to read Subject and Body. This process making workflow slower because I get 150 to 200 email daily.The API calling 200 times in a loop to get email Subject and Body with requesting date filter. Can I fetch date wise emails with specific Subject and Body filter? I want to read those mails only which has a specific Subject and Body. I know that I 'll get a specific type of mails on a daily basis I just want to read those emails only on the basis of from date and to date.Rohit Satpute

1 Answers

0
votes

The query seems like the most you can do. If you know more information about those emails, like a specific subjects or there always come from the same sender you can try to filter that too, like you would in the Gmail interface.

Other way you would be kind of out of luck. You are limited by the files retrieved from User.messages.list.

If you need to escape from the API limitations maybe trying to retrieve the message other way would be the correct way to go. Considerate creating a small code to retrieve message by the IMAP protocol. Several questions in this topic may help you: