如何使用Gmail API和Javascript发送结构化电子邮件标记?

时间:2016-04-23 13:29:23

标签: javascript gmail-api schema.org json-ld google-schemas

我正在尝试构建一个使用Gmail API发送电子邮件(自己)的Javascript应用,其中包括Gmail收件箱识别酒店预订所需的结构化数据。目标是能够在HTML表单中输入有关预订的详细信息,并让应用程序向我发送一封电子邮件,而不是收件箱,然后将其识别为酒店预订并在我的收件箱中添加旅行套装。

我使用了一个有效的示例here,该示例使用Google Apps脚本从我的帐户向我自己发送电子邮件。该脚本将文件作为html从文件中提取,包括JSON格式的必要结构化数据。这很好,Inbox可以识别酒店预订。

以下是Apps脚本代码:

function manuallyCreateTrips() {
  var htmlBody = HtmlService.createHtmlOutputFromFile('hotel').getContent();

  MailApp.sendEmail({
    to: Session.getActiveUser().getEmail(),
    subject: 'Somewhere ' + new Date(),
    htmlBody: htmlBody,
  });
}

这是电子邮件的html内容(hotel.html):

<html>
  <body>
    <script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "LodgingReservation",
  "reservationNumber": "None",
  "reservationStatus": "http://schema.org/Confirmed",
  "underName": {
    "@type": "Person",
    "name": "Richard Guy"
  },
  "reservationFor": {
    "@type": "LodgingBusiness",
    "name": "Somewhere",
    "address": {
      "@type": "PostalAddress",
      "streetAddress": "Street",
      "addressLocality": "Locality",
      "addressRegion": "Region",
      "postalCode": "Postcode",
      "addressCountry": "UK"
    },
    "telephone": "+44 1234 123123"
  },
  "checkinDate": "2016-04-27T13:00:00+01:00",
  "checkoutDate": "2016-04-28T12:00:00+01:00"
}
</script>


    <p>
      This is a hotel reservation at Somewhere.
    </p>
  </body>
</html>

但是我不想手动输入JSON,而是希望拥有更漂亮的界面。所以我开始使用Gmail的API在Javascript中构建一个简单的电子邮件客户端,遵循工作示例here。客户端可以正常发送我在Gmail帐户中收到的电子邮件。

以下是汇编和发送电子邮件的功能:

function sendEmail()
{
  $('#send-button').addClass('disabled');

  sendMessage(
    {
      'To': $('#compose-to').val(),
      'Subject': $('#compose-subject').val(),
      'Content-Type': 'text/html; charset=utf-8',
    },
    $('#compose-message').val(),
    composeTidy
  );

  return false;
}

function sendMessage(headers_obj, message, callback)
{
  var email = '';

  for(var header in headers_obj)
    email += header += ": "+headers_obj[header]+"\r\n";

  email += "\r\n" + message;

  var sendRequest = gapi.client.gmail.users.messages.send({
    'userId': 'me',
    'resource': {
      'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
    }
  });

  return sendRequest.execute(callback);
}

函数sendEmail()调用sendMessage(),传递包含标题行的对象,包含电子邮件(html格式)内容的字符串,以及后续整理的回调函数。 sendMessage()将标头与内容组合在一起,并将该批次编码为base64。我像以前一样发送电子邮件的相同html内容,电子邮件到达我的收件箱。正文中的任何html格式都会在我的电子邮件查看器中正确显示。但Gmail的收件箱似乎没有获取结构化数据,因此预订不会添加到新的旅行中。

当我比较两封电子邮件的来源时,我可以看到标题的显着差异。

这是成功的电子邮件:

Delivered-To: my@gmail.com
Received: by 10.79.103.71 with SMTP id b68csp826548ivc;
        Fri, 22 Apr 2016 09:09:32 -0700 (PDT)
X-Received: by 10.60.21.33 with SMTP id s1mr8900353oee.74.1461341372514;
        Fri, 22 Apr 2016 09:09:32 -0700 (PDT)
Return-Path: <3vEwaVwsJC30sjdibseuhvzhnbjm.dpnsjdibseuhvzhnbjm.dpn@maestro.bounces.google.com>
Received: from mail-ob0-x248.google.com (mail-ob0-x248.google.com. [2607:f8b0:4003:c01::248])
        by mx.google.com with ESMTPS id b134si2357523oih.30.2016.04.22.09.09.32
        for <my@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Fri, 22 Apr 2016 09:09:32 -0700 (PDT)
Received-SPF: pass (google.com: domain of 3vEwaVwsJC30sjdibseuhvzhnbjm.dpnsjdibseuhvzhnbjm.dpn@maestro.bounces.google.com designates 2607:f8b0:4003:c01::248 as permitted sender) client-ip=2607:f8b0:4003:c01::248;
Authentication-Results: mx.google.com;
       dkim=pass header.i=@gmail.com;
       spf=pass (google.com: domain of 3vEwaVwsJC30sjdibseuhvzhnbjm.dpnsjdibseuhvzhnbjm.dpn@maestro.bounces.google.com designates 2607:f8b0:4003:c01::248 as permitted sender) smtp.mailfrom=3vEwaVwsJC30sjdibseuhvzhnbjm.dpnsjdibseuhvzhnbjm.dpn@maestro.bounces.google.com;
       dmarc=pass (p=NONE dis=NONE) header.from=gmail.com
Received: by mail-ob0-x248.google.com with SMTP id js7so145982383obc.0
        for <richardtguy@gmail.com>; Fri, 22 Apr 2016 09:09:32 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=gmail.com; s=20120113;
        h=mime-version:message-id:date:subject:from:to;
        bh=L6yElux8juWH24FvYKyFSYm7hSo/j0YatA7rHQ62QZ4=;
        b=iUcZ/k5ctSENTTcliXUd1jyE8FnHigru+fx97U26V4ppudjHaWF5tgTXhHD9di+qu3
         dCTG/5uXRDZq/9lXox+zLGn1CUJv8otDjzyu4zQQzMCgFWkrlPvzauPCxmWMeqKBpsEN
         sbipWbMvTPMSLbUkzWNmC7aDqHEQffdlTu69+oEidkxBVGYYGHO6XWBNT78O9owYLUXD
         +7KzpEwciGDmdXkN+bFf9kFXsIapq7kHja3o3Y56Xz/lEeZDOYfOF211IhQ/ALWKEzpe
         uL3iOu1GItLVC6oUVt46d8qYxHfNtP0qmQXzNjuL4YC/XuFeR6eJQ8mXBj8pM8YkIfst
         1GYg==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=1e100.net; s=20130820;
        h=x-gm-message-state:mime-version:message-id:date:subject:from:to;
        bh=L6yElux8juWH24FvYKyFSYm7hSo/j0YatA7rHQ62QZ4=;
        b=QOSVkBTnwapvWbnMDhcvjyvrS84JL0QsG2vbckfUMLpFgjNcA5uw0QxZYRBLgYEjkT
         r3IvezvZqgtXES6QU6XUBnZQ8h7sVhgKGvB5t/b4BZbKbnkImGAhIhSQDqFtlY0+ZgqS
         GcuWs1eacvCKMfi5RKLvH6O1Bn63gEfdYtz3EjwfZdle1lvg9WvU3GSWt8G2Hw/Bb8Z2
         sYo3Ok4jwLFgdguCsJG8CK6eUKwAdLvgmrfU1oh0UJVDVGbWallEsVJPXW/iqAYvgOVr
         0BFsTMxKheruSLeKgx5PbUYYfOul8mLbYZz/NkLxU+hHuUd+zVvIvIPmidK+0CvMyGUB
         YFeA==
X-Gm-Message-State: AOPr4FVRMkINNmOkf3rYdLZspc+99SeliqYmKfw/6w4zvXITcXqVY/CP1fJO86bNJRLEPwl2jO4UMroedpRj6A==
MIME-Version: 1.0
X-Received: by 10.182.250.201 with SMTP id ze9mr14627612obc.0.1461341372044;
 Fri, 22 Apr 2016 09:09:32 -0700 (PDT)
Message-ID: <001a11c1fabe608d4f0531150d8c@google.com>
Date: Fri, 22 Apr 2016 16:09:32 +0000
Subject: Somewhere Fri Apr 22 2016 17:09:31 GMT+0100 (BST)
From: my@gmail.com
To: my@gmail.com
Content-Type: multipart/alternative; boundary=001a11c1fabe608d370531150d89

--001a11c1fabe608d370531150d89
Content-Type: text/plain; charset=ISO-8859-1; format=flowed; delsp=yes

Somewhere

--001a11c1fabe608d370531150d89
Content-Type: text/html; charset=ISO-8859-1

<html>
  <body>
    <script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "LodgingReservation",
  "reservationNumber": "None",
  "reservationStatus": "http://schema.org/Confirmed",
  "underName": {
    "@type": "Person",
    "name": "Richard Guy"
  },
  "reservationFor": {
    "@type": "LodgingBusiness",
    "name": "Somewhere,
    "address": {
      "@type": "PostalAddress",
      "streetAddress": "Address",
      "addressLocality": "Locality",
      "addressRegion": "Region",
      "postalCode": "Postcode",
      "addressCountry": "Country"
    },
    "telephone": "+12 1234 606630"
  },
  "checkinDate": "2016-04-23T13:00:00+01:00",
  "checkoutDate": "2016-04-24T12:00:00+01:00"
}
</script>


    <p>
      Somewhere
    </p>
  </body>
</html>
--001a11c1fabe608d370531150d89--

以下是Javascript应用使用Gmail API发送的电子邮件:

Received: from 760084270114
    named unknown
    by gmailapi.google.com
    with HTTPREST;
    Sat, 23 Apr 2016 09:43:29 -0400
To: my@gmail.com
Subject: Test reservation
Content-Type: text/html; charset=utf-8
Date: Sat, 23 Apr 2016 09:43:29 -0400
Message-Id: <CAD=04YmCHxH6mPY6FgoKLKFXd=C5sTLjQeo-9Q70jWKe4wVsRQ@mail.gmail.com>
From: my@gmail.com

<html>
  <body>
    <script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "LodgingReservation",
  "reservationNumber": "None",
  "reservationStatus": "http://schema.org/Confirmed",
  "underName": {
    "@type": "Person",
    "name": "Richard Guy"
  },
  "reservationFor": {
    "@type": "LodgingBusiness",
    "name": "Somewhere,
    "address": {
      "@type": "PostalAddress",
      "streetAddress": "Address,
      "addressLocality": "Locality",
      "addressRegion": "Region",
      "postalCode": "Postcode",
      "addressCountry": "UK"
    },
    "telephone": "+12 3456 606630"
  },
  "checkinDate": "2016-04-23T13:00:00+01:00",
  "checkoutDate": "2016-04-24T12:00:00+01:00"
}
</script>


    <p>
      Somewhere
    </p>
  </body>
</html>

任何想法??

1 个答案:

答案 0 :(得分:0)

最后,我发现在Google Apps脚本(GAS)网络应用中使用客户端JavaScript和Bootstrap样式实现合理优化的前端表单非常简单。服务器端功能处理发送嵌入了结构化数据的电子邮件。由于GAS的MailApp.sendEmail()功能会对电子邮件进行数字签名,因此这是成功的。我已将结果代码放在GitHub上并发布了网络应用here。谢谢你的建议!