10

I have this code that I am using in my application:

    private async Task configSendGridasync(IdentityMessage message)
    {
        var myMessage = new SendGridMessage();
        myMessage.AddTo(message.Destination);
        myMessage.From = new System.Net.Mail.MailAddress(
                            "[email protected]", "AB Registration");
        myMessage.Subject = message.Subject;
        myMessage.Text = message.Body;
        myMessage.Html = message.Body;

        var credentials = new NetworkCredential(
                   ConfigurationManager.AppSettings["mailAccount"],
                   ConfigurationManager.AppSettings["mailPassword"]
                   );

        // Create a Web transport for sending email.
        var transportWeb = new Web(credentials);

        // Send the email.
        if (transportWeb != null)
        {
            await transportWeb.DeliverAsync(myMessage);
        }
        else
        {
            Trace.TraceError("Failed to create Web transport.");
            await Task.FromResult(0);
        }
    }

It's called here:

    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {

        var user = new ApplicationUser()
        {
            Email = model.Email,
            FirstName = model.FirstName,
            LastName = model.LastName,
            RoleId = (int)ERole.Student,
            UserName = model.UserName
        };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            var callbackUrl = model.Server +
                              "/index.html" +
                              "?load=confirmEmail" +
                              "&userId=" + user.Id +
                              "&code=" + HttpUtility.UrlEncode(code);
            await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
        }
        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }
        return Ok();

    }

Is there any way I can get confirmation from sendgrid that the message has been sent or any other information?

3 Answers 3

13
+100

Emails sent via the SendGrid web API are asynchronous, so to get a confirmation, you need to implement a webhook. The Event Webhook will post events of your choice to a URL that you define. In this case you are interested in the "delivered" event.

You'll need some code on your server to handle the incoming webhook and do any logic based on the results, such as logging delivered events. There are a few community-contributed libraries out there that let you easily create a webhook handler. I suggest sendgrid-webhooks, which is available on nuget.

Then take the incoming POST and hand it to the parser to get an object back.

Since you are using ASP.NET MVC, then you can use an [HttpPost] method inside of a controller to receive the POST data from SendGrid. Then you can parse it using sendgrid-webhooks.

From the sendgrid-webhooks readme:

var parser = new WebhookParser();
var events = parser.ParseEvents(json);

var webhookEvent = events[0];

//shared base properties
webhookEvent.EventType; //Enum - type of the event as enum
webhookEvent.Categories; //IList<string> - list of categories assigned ot the event
webhookEvent.TimeStamp; //DateTime - datetime of the event converted from unix time
webhookEvent.UniqueParameters; //IDictionary<string, string> - map of key-value unique parameters

//event specific properties
var clickEvent = webhookEvent as ClickEvent; //cast to the parent based on EventType
clickEvent.Url; //string - url on what the user has clicked

I work at SendGrid so please let me know if there's anything I can help with.

1
  • Thanks very much. Great to have help from someone that works at SendGrid. I will wait a while, test out your solution and let you know if I have any questions. Jul 6, 2015 at 15:19
6

You will want to use Event Webhooks to get confirmation sent back to you to confirm the message has been delivered to the recipient.

You would need to setup a page to accept events from Sendgrid, such as:

https://yourdomain.com/email/hook which would accept JSON which you would then deal with however you want. The Json.NET documentation would be able to guide you with how to accept JSON and then turn it into an object you can use.

Example JSON you'd be POSTed:

{
    "sg_message_id":"sendgrid_internal_message_id",
    "email": "[email protected]",
    "timestamp": 1337197600,
    "smtp-id": "<[email protected]>",
    "event": "delivered"
  },

The events you can receive from SendGrid are: Processed, Dropped, Delivered, Deferred, Bounce, Open, Click, Spam Report, Unsubscribe, Group Unsubscribe, Group Resubscribe.

With all these options you could have a webhook to deal with Bounces such as get someone to find out the correct e-mail address for the user you tried to email.

2
  • I'll wait a while and review all the answers and accept the one that best explains for everyone. Thank you very much for taking the time to answer the question. Jul 6, 2015 at 15:17
  • How do i pair the webhook with what i sent? When i did send the mail, there is no sg_messge_id as a response for me to keep and match with webhook return.
    – chaintng
    Nov 12, 2015 at 4:26
-1

I dont think SendGrid is set up to give a response. However, as a hack, you could BCC yourself (and therefore know at least email has gone out) by adding the following code to your configSendGridasync class

    .
    .
    .
    //this is your old code...
    myMessage.Text=message.Body;
    myMessage.Html = message.Body;

    //Add this...
    myMessage.AddBcc("[email protected]");

Hope this helps!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.