首页 > 解决方案 > 使用 Google Apps 脚本时使用查询参数保护 URL

问题描述

我很难发送包含包含查询参数的 URL 的自动电子邮件(使用 Google Apps 脚本)。

预期行为

Google Apps 脚本(特别是Gmail服务)发送一封电子邮件,电子邮件正文的一部分包含一个带有查询参数的 URL。URL 如下所示: http://my.app/products?id= Bz9n7PJLg8hufTj11gMF

观察到的行为

Gmail服务似乎正在=从我的 URL 中删除。因此,电子邮件的正文最终看起来像这样: ... http://my.app/products?idBz9n7PJLg8hufTj11gMF ...

显然,该链接不起作用。

我在这里检查了关于 SO 的其他问题,我尝试使用 GAS Utilities 服务中的基本编码工具,以及使用encodeURI()JavaScript 方法。到目前为止没有运气。

电子邮件发送代码

    //////// 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 = 'hello@gmail.com'
    let creatorUsername = 'Sam'
    template = template.replace(/templates@my.app/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"))

标签: javascriptgoogle-apps-scriptgmailgmail-apiurlencode

解决方案


基于正则表达式的解决方案

在TanaikeRafa Guillermo的帮助下,最终为我工作的解决方案是使用以下代码=替换: =.replace()listingUrl = listingUrl.replace(/=/, '=')


推荐阅读