Post textarea tag data with new line fail when posting json data to SendGrid API v3 in classic asp

Viewed 191

I try to post textarea data in html which can inclueds new line as Content of text/plain of Sendgrid API. But it doesn't make it at all.. I need some help.

■Html

Textarea tag in form

■ServerSide Program(ASP) Post text area data to Sendgrid as body

'Send Mail with SendGrid
    Sub SendMailWithApiKey(strTo,strFrom,strTitle,strBody)
        Set xmlhttp = CreateObject("Msxml2.ServerXMLHTTP.6.0")
        xmlhttp.open "POST", "https://api.sendgrid.com/v3/mail/send", false
        xmlhttp.setRequestHeader "Authorization", "Bearer Some API Key of sendgrid"
        xmlhttp.SetRequestHeader "Content-Type", "application/json"
        xmlhttp.SetRequestHeader "X-Requested-With", "XMLHttpRequest"
        xmlhttp.send "{ ""personalizations"": [ { ""to"": [{""email"": """ & strTo &"""}] } ], ""from"": {""email"": """ & strFrom &"""}, ""subject"": """ & strTitle &""", ""content"": [ { ""type"": ""text/plain"", ""value"": """ & strBody &""" }] }"
        Response.AddHeader "Content-Type", "application/json;charset=UTF-8"
        Response.Charset = "UTF-8"
        pageReturn = xmlhttp.responseText
                Response.AppendToLog xmlhttp.responseText
        Set xmlhttp = Nothing 
        response.write pageReturn
    End Sub

The "strBody" is Value of textarea user write.

If I write one line like just "test", it work well and got mail. But it fails when I write like below in text area.

"test
test
test "

I got 400 error from sendgrid.

{"errors":[{"message":"Bad+Request","field":null,"help":null}]}

Do I need someting to resolve error?

I appliciate your help.

1 Answers

Remember encountering this issue while building a Classic ASP Script Library for the SendGrid API, as the error returned isn't very useful it took a little bit of diagnosing the problem.

The issue is because SendGrid expects JSON as it's input, so passing a multiline string (containing carriage return, linefeed etc) will break the JSON parse. To fix this, just do a replace on the strBody to convert the line endings to \n.

Something like this, before you call the Send() method;

strBody = Replace(strBody & "", vbCrLf, "\n")

You may find you need to do the same for other values;

strBody = Replace(strBody & "", vbCrLf, "\n")
strBody = Replace(strBody & "", vbTab, "\t")

If you are using HTML you will want to convert your line endings to HTML line breaks <br />.

Again this just requires a Replace();

strBody = Replace(strBody & "", vbNewLine, "<br />")

Useful Links

Related