1

This is regarding Sendgrid incoming mail webhook, I have referred this URL SendGrid incoming mail webhook - how do I secure my endpoint, and got some idea how to go about this, but, as I am new to MVC / WebAPI, could anyone give me the controller method code snippet to catch the JSON format HTTP post and save to my application folder.

Community
  • 1
  • 1
  • All the examples you need for C# and the Inbound Parse Webhook can be found in the SendGrid documentation: https://sendgrid.com/docs/Integrate/Code_Examples/Webhook_Examples/csharp.html – Martyn Davies Jul 17 '15 at 14:51
  • I have referred this document, here the help provides how to parse the inbound email, but I require help regarding the step before this to catch the email (HTTPRequest) in JSON format sent from the sendgrid in the webapi controller, once I have that snippet I can go ahead with the aforementioned help link., thank you. – Mallesh Telagarapu Jul 20 '15 at 02:20

2 Answers2

1

This is the solution I found after googling and with slight modifications:

[HttpPost, HttpGet]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public async Task Post()
{
    if (Request.Content.IsMimeMultipartContent("form-data"))
        try
        {
            //To get complete post in a string use the below line, not used here
            string strCompletePost = await Request.Content.ReadAsStringAsync();

            HttpContext context = HttpContext.Current;
            string strFrom = context.Request.Form.GetValues("from")[0];
            string strEmailText = context.Request.Form.GetValues("email")[0];
            string strSubject = context.Request.Form.GetValues("subject")[0];

            //Not useful I guess, because it always return sendgrid IP
            string strSenderIP = context.Request.Form.GetValues("sender_ip")[0];
        }
        catch (Exception ex)
        {

        }
}

I tried, retrieving the values as

String to = context.Request.Params["to"];

but, the value returned is not consistent, i.e. most of the times it is returning null and occasionally returns actual value stored in it.

If anyone have a better solution, please let me know.

Thank you

1

If for some reason ["to"] doesn't work for you, try to get ["envelope"] value,

context.Request.Form.GetValues("envelope")[0]

which looks like

{"to":["emailto@example.com"],"from":"emailfrom@example.com"}
Dmitri Usanov
  • 348
  • 4
  • 11