Search code examples
javascriptgoogle-apps-scriptgmailgmail-apiurlencode

Protecting a URL with a Query Parameter when Using Google Apps Script


I'm having a really hard time sending an automated email (with Google Apps Script) that includes a URL that contains query parameter.

Expected Behavior

Google Apps Script (specifically, the Gmail service) sends an email, and part of the email body contains a URL with a query parameter. The URL will look something like this: http://my.app/products?id=Bz9n7PJLg8hufTj11gMF

Observed Behavior

The Gmail service seems to be stripping out the = from my URL. So, the body of the email ends up looking like this: ... http://my.app/products?idBz9n7PJLg8hufTj11gMF ...

Obviously, that link won't work.

I've checked other questions here on SO, and I've tried working with the base encoding tools from the GAS Utilities service, as well as working with the encodeURI() JavaScript method. No luck so far.

Email-sending Code

    //////// GENERATING MESSAGE FROM ID ////////////
    // Gets message from ID
    var id = Gmail.Users.Drafts.get('me', 'r-1006091711303067868').message.id
    var message = GmailApp.getMessageById(id)
    var template = message.getRawContent()
    
    // Replaces template variables with custom ones for the user using RegExes
    let listingUrl = 'http://my.app/products?id=xyz'
    let creatorEmail = '[email protected]'
    let creatorUsername = 'Sam'
    template = template.replace(/[email protected]/g, creatorEmail)
    template = template.replace(/firstName/g, creatorUsername)
    //** Below is the string that gets modified and broken **//
    template = template.replace(/listingUrl/g, listingUrl)
    
    // Creates the new message
    var message = Gmail.newMessage()
    var encodedMsg = Utilities.base64EncodeWebSafe(template)
    message.raw = encodedMsg
    
    // Sends it
    Gmail.Users.Messages.send(message, "me", Utilities.newBlob(template, "message/rfc822"))

Solution

  • Regex-based Solution

    With the help of Tanaike and Rafa Guillermo, the solution that ended up working for me was to replace = with = by using a little .replace() like this: listingUrl = listingUrl.replace(/=/, '=')