sendgrid / sendgrid-csharp

The Official Twilio SendGrid C#, .NetStandard, .NetCore API Library
https://sendgrid.com
MIT License
1.08k stars 585 forks source link

Issue with adding Templates with SendGrid Helper Class #979

Closed greenrhome closed 4 years ago

greenrhome commented 4 years ago

I recently added SendGrid to my ASP.net Core 2.2 MVC project. In order to make the automated account confirmation and password reset emails more professional I've tried to implement the dynamic templates. Email was working fine before, but as soon as I added the Template ID using the SendGrid helper, the emails won't send. When I remove the template ID, everything works fine again. I've sent the JSON snippet (i think that's what it's called?) to SendGrid support and they said it runs fine on their end, so something is stopping it from executing in the program. I've tried adding and removing subject and content in case it didn't like that, but that didn't change anything. My code is below. Thank you so much for any help or ideas to try.

public interface IEmailSender
{
    Task SendEmailAsync(string email, string subject, string message);
}

public Task SendEmailAsync(string email, string subject, string message)
{
    return Execute(Options.SendGridKey, email);
}

public Task Execute(string apiKey, string email)
{

    var client = new SendGridClient(apiKey);
    var msg = new SendGridMessage()
    {
        From = new EmailAddress("FROM EMAIL ADDRESS", "SENDER NAME"),
        Subject = "testtest",
        PlainTextContent = "test1",
        HtmlContent = "test2"

    };
    msg.AddTo(new EmailAddress(email));

// removing the msg.SetTemplateId line allows email to start working again.  Adding it back in breaks it.
    msg.SetTemplateId("MY TEMPLATE ID");

    // Disable click tracking.
    // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
    msg.SetClickTracking(false, false);
    var debug = (msg.Serialize());
    return client.SendEmailAsync(msg);
}

public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            await _emailSender.SendEmailAsync(model.Email, "EMAIL SUBJECT",
                $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}
childish-sambino commented 4 years ago

Can you post the JSON here? And are you getting any errors?

greenrhome commented 4 years ago

See below. The only change to my code isremoving the msg.settemplateid line.

With the template ID present, no email received:

"{\"from\":{\"name\":\"Greenr\",\"email\":\"greenrhome@gmail.com\"},\"subject\":\"testtest\",\"personalizations\":[{\"to\":[{\"email\":\"greenrhome+ver40@gmail.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"test1\"}],\"template_id\":\"d-c86094b06c384330819164d1ae46c42f\",\"tracking_settings\":{\"click_tracking\":{\"enable\":false,\"enable_text\":false}}}"

with template id removed, email received: "{\"from\":{\"name\":\"Greenr\",\"email\":\"greenrhome@gmail.com\"},\"subject\":\"testtest\",\"personalizations\":[{\"to\":[{\"email\":\"greenrhome+ver41@gmail.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"test1\"}],\"tracking_settings\":{\"click_tracking\":{\"enable\":false,\"enable_text\":false}}}"

childish-sambino commented 4 years ago

What status code is being returned? And are there any errors you're seeing or is the email just not getting delivered?

greenrhome commented 4 years ago

My apologies, I'm still very novice with all of this. How would I get the status code? I'm not getting any errors in visual studio or through the browser. Also, this code is triggered when a new account is created, and the account is still created fine. It's just a matter of if the email is delivered or not.

On Thu, Feb 27, 2020, 07:14 childish-sambino notifications@github.com wrote:

What status code is being returned? And are there any errors you're seeing or is the email just not getting delivered?

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/sendgrid/sendgrid-csharp/issues/979?email_source=notifications&email_token=AOUY6IFA63KG6ZQIGG3MATLRE6VBHA5CNFSM4K22ZX2KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOENEESFY#issuecomment-591939863, or unsubscribe https://github.com/notifications/unsubscribe-auth/AOUY6IHZ2DO3Y4A22DAOA7DRE6VBHANCNFSM4K22ZX2A .

childish-sambino commented 4 years ago

There's some information here about accessing the response status code: https://github.com/sendgrid/sendgrid-csharp/blob/master/TROUBLESHOOTING.md#error-messages

greenrhome commented 4 years ago

I'm not sure if I did it right, but here are the status codes for with and without the template id:

Without template id Statuscode: System.Net.HttpStatusCode.Accepted Result: "" Headers: "Server: nginx\r\nDate: Tue, 03 Mar 2020 03:21:58 GMT\r\nConnection: keep-alive\r\nX-Message-Id: dZVDPltfTPafKCsEuO157g\r\nAccess-Control-Allow-Origin: https://sendgrid.api-docs.io\r\nAccess-Control-Allow-Methods: POST\r\nAccess-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl\r\nAccess-Control-Max-Age: 600\r\nX-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html\r\n"

With template id Statuscode: System.Net.HttpStatusCode.Accepted Result: "" Headers: "Server: nginx\r\nDate: Tue, 03 Mar 2020 03:31:07 GMT\r\nConnection: keep-alive\r\nX-Message-Id: aNfXt27DReuox8y2DYj_NQ\r\nAccess-Control-Allow-Origin: https://sendgrid.api-docs.io\r\nAccess-Control-Allow-Methods: POST\r\nAccess-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl\r\nAccess-Control-Max-Age: 600\r\nX-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html\r\n"

childish-sambino commented 4 years ago

Looks like you're getting back a 202/Accepted so the backend is receiving the request properly. Given that, there's not much that can be done from the client without more debugging info. Suggest reaching back out to support with these additional details so they may further help to debug what's going on here.

thinkingserious commented 4 years ago

Hello @greenrhome,

Thanks for submitting a GitHub issue! We are very sorry that you are running into this problem. In order to better serve you, as this does not present itself as a library specific issue, we would like to ask that you reach out to our support team at https://support.sendgrid.com.

Thank you!

SendGrid DX Team