Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can my ASP.Net Code get confirmation from sendgrid that an email has been sent?

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?

like image 360
Samantha J T Star Avatar asked Jul 04 '15 08:07

Samantha J T Star


People also ask

How does SendGrid email work?

SendGrid is a cloud-based SMTP provider that allows you to send email without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to whitelist services and real time analytics.

Is SendGrid an email provider?

SendGrid is the world's largest email infrastructure as a service provider. We send over 100 billion non-spam emails a month for over 80,000 paying customers including technology leaders like AirBnB, Spotify, and Uber.


2 Answers

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.

like image 137
bwest Avatar answered Oct 19 '22 14:10

bwest


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.

like image 44
Ryan McDonough Avatar answered Oct 19 '22 16:10

Ryan McDonough