Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #760 #763

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/SendGrid/SendGridClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// </copyright>

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SendGrid.Helpers.Mail;
using SendGrid.Helpers.Reliability;
using System;
Expand Down Expand Up @@ -214,6 +215,23 @@ public async Task<Response> 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)
Expand Down
16 changes: 16 additions & 0 deletions tests/SendGrid.Tests/Integration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6125,6 +6125,22 @@ public async Task TestRetryBehaviourSucceedsOnSecondAttempt()

Assert.Equal(HttpStatusCode.OK, result.StatusCode);
}

[Fact]
public async Task TestUsingInvalidTemplateIdThrowsException()
{
var headers = new Dictionary<string, string> { { "X-Mock", "404" } };
var sg = new SendGridClient(fixture.apiKey, fixture.host, headers);
var msg = new SendGridMessage();
msg.SetFrom(new EmailAddress("[email protected]"));
msg.AddTo(new EmailAddress("[email protected]"));
msg.SetSubject("Hello World from the SendGrid CSharp Library");
msg.SetTemplateId("1000");

var exception = await Assert.ThrowsAsync<Exception>(() => sg.SendEmailAsync(msg));

Assert.NotNull(exception);
}
}

public class FakeWebProxy : IWebProxy
Expand Down