Search code examples
c#.netsendgrid

Cancelling BatchId in SendGrid Using C# API


I am currently implementing a series of API calls that will schedule emails through the SendGrid API. As such, these emails will be going to a distribution list, and have the possibility of needing to be rescheduled based on business user needs. As such, I have been attempting to assign a BatchId to the SendGridMessage and then later, cancel that message utilizing the BatchId.

Unfortunately, I am continuing to get either error codes, or results from the API that don't quite make sense. For instance, I successfully schedule the email (I know it's successful because I receive the email when the time is reached. I also know the batchID is sent with the message, because I am setting the categories). Once scheduled, I should be able to take the batchId and cancel the batch. But, I am getting an invalid batch_id error message. So I run the GET command to check scheduled_sends, and nothing is returned.

Please see the code below, and let me know if you have any questions or concerns. Thank you.

C# Code Interacting With SendGrid C# Package

    message.BatchId = sendGridBatchID;

    if (sendAt != 0)
    {
        message.SendAt = sendAt;
    }
    var apiKey = _configuration.GetSection("NewSendGridAPIKey").Value;
    var client = new SendGridClient(apiKey);
    var response = await client.SendEmailAsync(message).ConfigureAwait(false);
    return response.IsSuccessStatusCode;

C# Code to Generate a New Batch ID

        string apiKey = GetAPIKey();
        SendGridClient client = GetSendGridClient(apiKey);
        var batchId = default(string);

        var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "mail/batch");
        if (response.StatusCode == HttpStatusCode.Created)
        {
            JObject joResponse = JObject.Parse(response.Body.ReadAsStringAsync().Result);
            batchId = (((Newtonsoft.Json.Linq.JValue)joResponse["batch_id"]).Value).ToString();
        }
        return batchId;

Curl command to see if the scheduled batch can be cancelled

curl --location --request POST 'https://api.sendgrid.com/v3/user/scheduled_sends' \
--header 'Authorization: Bearer <<API_KEY>>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "batch_id": "<BATCH_ID>",
    "status":"cancel"
}'

Return result from above curl command

{"errors": [{
    "field": "batch_id",
    "message": "invalid batch id"
 }]}

Edit: Overall workflow concept Generate email batchID --> Schedule email with batchID --> (Prolonged Wait) --> User wants to cancel batch --> Cancel email with previous batchID --> Gen new batchID and reschedule the existing email.


Solution

  • Closing this issue as I believe I was not scheduling the emails out far enough for me to actually cancel them. SendGrid mentions that cancel requests sent before 10 minutes of the send_at time, are not guarenteed to get cancelled. I also noticed that when using the user/scheduled_sends endpoint, there is a delay in when the cancel call is made, and when the batch_id ends up in the list.