Search code examples
javascriptjqueryhtmlmailto

Passing special characters to mailto body blows up JavaScript


I have a C# ASP.NET app that creates a JavaScript array of values for some user profile information. Client-side, I use jQuery/JavaScript to read the array and generate a mailto link. Some of the fields can contain special characters, such as ' & = / \ ".

Here's the C# code:

private String generateElementsArray(){
  StringBuilder sb = new StringBuilder();
  sb.Append("var currentElements = { currentUserName: '");
  sb.Append(currentUserName);
  sb.Append("', currentUserEmail: '");
  sb.Append(currentUserEmail);
  sb.Append("', currentSite: '");
  sb.Append(currentSite);
  sb.Append("', currentTitle: '");
  sb.Append(currentTitle);
  sb.Append("'}");
  return sb.ToString();
}    

I write the value of the above method to the page, which produces this JavaScript:

<script type="text/javascript">var currentElements = { currentUserName: 'Alex', currentUserEmail: 'myemailID', currentSite: 'Helpdesk', currentTitle: 'Phone User Guides & Troubleshooting'}</script>

Then I generate the email link using this JavaScript code, attaching the anchor tag to an element on the page:

function generateEmailTo(){
  var body = currentElements.currentUserName + ' has shared a page with you on the intranet.%0A%0APage Title: %22' +
    currentElements.currentTitle.replace("&","and")  + '%22%0A' + $(location).attr('href').replace('#',''); 
  var subject = currentElements.currentUserName + ' has shared a page with you on the intranet';
  var mailto = 'mailto: ?body=' + body + '&subject=' + subject;
  var anchor = '<a href="' + mailto + '"></a>';

  $("#email-placeholder").wrap(anchor);
}
....

<img id="email-placeholder" title="Send this page to a friend." src="<%= baseUrl %>/SiteAssets/media/icons/email-icon.gif"/>

For the mailto body text, I've noticed that it only takes a small set of the encoded characters, such as %22 for double-quotes, and %0A for line breaks. How do I pass the special characters such as single quotes, ampersands, etc., to the mailto body text and keep JavaScript happy?


Solution

  • Mailto is a URI scheme so all of its components must be URI encoded. You can use JavaScript encodeURIComponent function to encode mailto components. Please see the following example:

    function buildMailTo(address, subject, body) {
        var strMail = 'mailto:' + encodeURIComponent(address)
                       + '?subject=' + encodeURIComponent(subject)
                       + '&body=' + encodeURIComponent(body);
        return strMail;
    }
    var strTest = buildMailTo('[email protected]', 'Foo&foo', 'Bar\nBar');
    /* strTest should be "mailto:abc%40xyz.com?subject=Foo%26foo&body=Bar%0ABar" */
    window.open(strTest);
    

    Hope this help.