Search code examples
emailvbscriptasp-classichtml-emailmailgun

How to send '&' symbol in email subject/html body using mailgun API?


I have implemented mailgun API method to send emails throughout my site using classic ASP as said in this link. But when we try to send '&' symbol in the subject/text/htmlbody the text after '&' symbol are not sending in the email.

For example : If we try to send subject as "A&B Traders" but the email sent using the mailgun API will show the subject as "A".

Problem occurs due to we are sending the parameters using query string seperated by & to the mailgun API is there a way to bypass '&' symbol in the content and send in the query string value but it should be received as & in the email.

I searched a lot but can't able to find any solution in mailgun API documentation.

Sample code to send email :

Function SendMailSync(toAddress, fromAddress, subject, body, htmlBody)
Dim httpPostData
Dim mailGunMessageUrl
Const MAILGUN_BASE_URL = "https://api.mailgun.net/v3/{DOMAIN HERE}"
Const MAILGUN_API_KEY = "key-{API_KEY}"
httpPostData = "from=" & fromAddress
httpPostData = httpPostData & "&to=" & toAddress
httpPostData = httpPostData & "&subject=" & subject
httpPostData = httpPostData & "&text=" & body
httpPostData = httpPostData & "&html=" & htmlBody
set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
mailGunMessageUrl = MAILGUN_BASE_URL & "/messages"
http.Open "POST", mailGunMessageUrl, false, "api", MAILGUN_API_KEY
http.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.setRequestHeader "Authorization", "Basic AUTH_STRING"
http.Send httpPostdata
If http.status <> 200 Then
    Response.Write "An error occurred: " & http.responseText
End If
SendMailSync = http.responseText
Set http = Nothing
End Function
SendMailSync "[email protected]", "No Reply [email protected]", "A&B Traders", "A&B Traders Welcomes You", ""

Solution

  • Modify the SendMailAsync() function so that you Server.UrlEncode() each value passed. For example with the subject, just change it to;

    httpPostData = httpPostData & "&subject=" & Server.UrlEncode(subject)
    

    that way, when the URL is sent the subject query string parameter will look like;

    &subject=A%26B%20Traders
    

    If you want to test the approach yourself you can use an online URL decode / encode page like the URL Decoder/Encoder.

    Whenever manually sending data via a Http Request you should URL encode all parameters so things like conflicts with special characters like ? and & etc don't happen. When you submit a standard form the Internet Browser does this as part of its process, which is why some may not be familiar with why it is required when sending manual requests.


    Useful Links