2015-07-04 10 views
9

Ho questo codice che sto usando nella mia domanda:Il mio codice ASP.Net può ottenere conferma da sendgrid che è stata inviata una e-mail?

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); 
     } 
    } 

Si chiama qui:

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(); 

    } 

C'è un modo posso ottenere la conferma da SendGrid che il messaggio è stato inviato o qualsiasi altre informazioni?

risposta

11

Le e-mail inviate tramite l'API Web SendGrid sono asincrone, quindi per ottenere una conferma, è necessario implementare un webhook. Lo Event Webhook pubblicherà eventi di tua scelta su un URL che hai definito. In questo caso sei interessato all'evento "consegnato".

Avrai bisogno di un codice sul server per gestire il webhook in entrata e fare qualsiasi logica basata sui risultati, come la registrazione degli eventi consegnati. Ci sono alcune librerie fornite dalla comunità che ti permettono di creare facilmente un gestore webhook. Suggerisco sendgrid-webhooks, che è disponibile su nuget.

Quindi prendere il POST in arrivo e consegnarlo al parser per ottenere un oggetto indietro.

Poiché si utilizza ASP.NET MVC, è possibile utilizzare un metodo [HttpPost] all'interno di un controller per ricevere i dati POST da SendGrid. Quindi puoi analizzarlo usando sendgrid-webhooks.

Dal 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 

Io lavoro in SendGrid quindi per favore fatemi sapere se c'è qualcosa che posso aiutare con.

+0

Grazie mille. Ottimo per avere aiuto da qualcuno che lavora su SendGrid. Aspetterò un po ', testare la tua soluzione e farti sapere se ho qualche domanda. –

-1

Non penso che SendGrid sia impostato per fornire una risposta. Tuttavia, come un hack, si potrebbe BCC te stesso (e quindi conoscere almeno email va) aggiungendo il seguente codice alla classe configSendGridasync

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

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

Spero che questo aiuti!

5

Si vorrà utilizzare Event Webhooks per ottenere la conferma di ritorno a voi per confermare il messaggio è stato consegnato al destinatario.

Si avrebbe bisogno di impostare una pagina di accettare gli eventi da SendGrid, come ad esempio:

https://yourdomain.com/email/hook che accettare JSON, che si sarebbe poi affrontare nel modo desiderato. La documentazione Json.NET sarebbe in grado di guidarti con come accettare JSON e poi trasformarlo in un oggetto che puoi usare.

Esempio JSON sareste Inviato:

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

Gli eventi si può ricevere da SendGrid sono: fusi, Dropped, Consegnato, differite, Bounce, Open, Click, Spam Report, Cancellati, Gruppo Cancellati, Riscrivi il gruppo.

Con tutte queste opzioni è possibile avere un webhook per gestire i rimbalzi, ad esempio chiedere a qualcuno di trovare l'indirizzo e-mail corretto per l'utente che ha provato a inviare tramite e-mail.

+0

Aspetterò un po 'e ripasso tutte le risposte e accetto quello che meglio spiega per tutti.Grazie mille per aver trovato il tempo di rispondere alla domanda. –

+0

Come faccio ad accoppiare il webhook con quello che ho inviato? Quando ho inviato la posta, non c'è 'sg_messge_id' come risposta per me per mantenere e abbinare il ritorno di webhook. – chaintng

Problemi correlati