diff --git a/src/SendGrid/SendGridClient.cs b/src/SendGrid/SendGridClient.cs index cceb3a76d..6b9617299 100644 --- a/src/SendGrid/SendGridClient.cs +++ b/src/SendGrid/SendGridClient.cs @@ -4,6 +4,7 @@ // using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using SendGrid.Helpers.Mail; using SendGrid.Helpers.Reliability; using System; @@ -214,6 +215,23 @@ public async Task RequestAsync( { var endpoint = this.client.BaseAddress + this.BuildUrl(urlPath, queryParams); + // Additional validation if the request is a mail/send request + if (urlPath.ToLower() == "mail/send" && !string.IsNullOrWhiteSpace(requestBody)) + { + var body = JObject.Parse(requestBody); + var template_id = (string)body["template_id"]; + + // If a template ID is provided and the account has GET access to tokens, check that the token exists + if (!string.IsNullOrWhiteSpace(template_id)) + { + var response = await this.RequestAsync(Method.GET, urlPath: $"templates/{template_id}"); + if (response.StatusCode == HttpStatusCode.NotFound) + { + throw new Exception("The provided template_id does not exist for this account."); + } + } + } + // Build the request body StringContent content = null; if (requestBody != null) diff --git a/tests/SendGrid.Tests/Integration.cs b/tests/SendGrid.Tests/Integration.cs index 1056df0a7..cf75d9560 100644 --- a/tests/SendGrid.Tests/Integration.cs +++ b/tests/SendGrid.Tests/Integration.cs @@ -6125,6 +6125,22 @@ public async Task TestRetryBehaviourSucceedsOnSecondAttempt() Assert.Equal(HttpStatusCode.OK, result.StatusCode); } + + [Fact] + public async Task TestUsingInvalidTemplateIdThrowsException() + { + var headers = new Dictionary { { "X-Mock", "404" } }; + var sg = new SendGridClient(fixture.apiKey, fixture.host, headers); + var msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.AddTo(new EmailAddress("test@example.com")); + msg.SetSubject("Hello World from the SendGrid CSharp Library"); + msg.SetTemplateId("1000"); + + var exception = await Assert.ThrowsAsync(() => sg.SendEmailAsync(msg)); + + Assert.NotNull(exception); + } } public class FakeWebProxy : IWebProxy