Sendgrid-csharp: SendEmailAsync call in library not returning response when called from C# other project

Created on 27 Feb 2017  路  3Comments  路  Source: sendgrid/sendgrid-csharp

Issue Summary

I have written a base library send call using SendGrid 9.0.12 and SendGrid C# HTTP 3.0 (see code below). This works when tests are run against it, or if I take it out of the library and run it directly from my web code. However, if I call it from my C# web code (see second code chunk below), the SendEmailAsync call never returns a result (though the email is sent). Any ideas?

Library Call

public async Task<string> SendEmail(string toAddresses, string fromEmailAddress, string fromName, string bccAddresses, string subject, string templateId, string bodyContent, Dictionary<string,string> substitutions)
{
 var message = new SendGridMessage();
            message.From = new EmailAddress(fromEmailAddress, name: string.IsNullOrEmpty(fromName) ? null : fromName);
            message.Subject = subject;
            if(!string.IsNullOrEmpty(templateId)) message.TemplateId = templateId;

            message.AddTos(GetEmailAddressListFromCommaSeparatedEmails(toAddresses));
            if(!string.IsNullOrEmpty(bccAddresses)) message.AddBccs(GetEmailAddressListFromCommaSeparatedEmails(bccAddresses));

            message.AddSubstitutions(substitutions);

            var client = new SendGridClient(apiKey);
            var response = await client.SendEmailAsync(message);
            return response.StatusCode.ToString();
}

C# Web Code

        public async Task<string> SendValidationEmail(string toAddress, string code, Guid invitationId)
{
var verificationUrl = string.Format("{0}/account/verify/{1}", ConfigurationManager.AppSettings["SiteUrl"], invitationId.ToString());
            var substitutions = new Dictionary<string, string>
            {
                { "-verificationurl-", verificationUrl},
            {"-code-", code }
        };
            var result = sender.SendEmail(
                toAddresses: toAddress,
                fromEmailAddress: ConfigurationManager.AppSettings["FromEmail"],
                fromName: ConfigurationManager.AppSettings["FromName"],
                subject: "Your Calfee Connect Verification Code",
              templateId: "94bae6c6-2d25-47b2-9198-21215e76d4a9",
              bccAddresses: string.Empty,
              bodyContent: string.Empty,
              substitutions: substitutions
              ).Result;
return result;
}

Steps to Reproduce

  1. Set up project with SendEmail call
  2. Test - works using separate test calls (NUnit Fixture)
  3. Make MVC project with reference to project with SendEmail call
  4. Call SendEmail - tracing, it does not get a response, though email is sent

Technical details:

  • sendgrid-csharp Version: 3.0.0
  • sendgrid versio: 9.0.12
  • .NET Version: 4.5.2
  • Visual Studio 2015
  • Chrome

Most helpful comment

Making it a non-async call seems to have fixed it.

All 3 comments

Making it a non-async call seems to have fixed it.

Hello @mhagesfeld,

I was able to get it working with a very simple "ASP.NET Web Forms Project" targeting .NET 4.5.2.

I changed the code in Default.aspx.cs to:

using System;
using System.Web;
using System.Web.UI;
using SendGrid;
using SendGrid.Helpers.Mail;
using System.Threading.Tasks;

namespace TestingWebForms
{

    public partial class Default : System.Web.UI.Page
    {
        public void button1Clicked(object sender, EventArgs args)
        {
            var response = Execute();
            Response result = response.Result;
            button1.Text = result.Body.ReadAsStringAsync().Result;
        }

        public static async Task<Response> Execute()
        {
            var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
            var client = new SendGridClient(apiKey);
            var from = new EmailAddress("[email protected]", "DX ");
            var subject = "Hello World from the SendGrid CSharp SDK!";
            var to = new EmailAddress("[email protected]", "Elmer Thomas");
            var plainTextContent = "Hello, Email!";
            var htmlContent = "<strong>Hello, Email!</strong>";
            var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);
            return response;
        }
    }
}

Upon success, the button will be empty (we don't return a body on successful mail/send call) and you will have received the email. If there was an issue, the button will contain the error.

I know this is closed. It's worth mentioning I had this issue and resolved it in the same way. Just straight up not responding isn't the expected behaviour of any .NET networking client. This should be fixed.

Was this page helpful?
0 / 5 - 0 ratings