【问题标题】:Format for adding attachment to mail in gmail api在gmail api中添加附件到邮件的格式
【发布时间】:2017-11-10 17:39:27
【问题描述】:

我正在尝试使用 gmail api(link to api doc) 创建草稿

我发送请求正文如下,

    {
  "id": "001",
  "message": {
    "raw": "VG86IGZvb0BleGFtcGxlLmNvbQ0KU3ViamVjdDpJZ25vcmUNCg0KdGVzdCBtYWlsIGJvZHkNCg==",
    "payload": {
      "headers": [

      ],
      "mimeType": "message/rfc822"
    }
  }
}

其中raw包含以下base64编码的字符串,

 To: foo@example.com
Subject:Ignore

test mail body

这工作正常,但我正在努力将附件添加到邮件中。我尝试了以下方法,但它不起作用,

 To: foo@example.com
Subject:Ignore

test mail body
Content-Type: multipart/mixed; boundary=##########


--##########

Content-Type: text/html; charset=UTF-8

 test mail body  

 --##########

Content-Type : image/png
Content-Disposition: attachment; filename=sample.png
Content-Transfer-Encoding: base64


[B@66d3c617

 --##########

谢谢。

【问题讨论】:

  • 已经有了答案,但还有一个问题:[B@66d3c617 是byte[].toString()。因为那是Base64,你可以做new String(bytes, StandardCharsets.US_ASCII)。
  • 谢谢,是的,我无法对附件进行编码,请问我们应该如何编码?假设它是一个图像,首先将其转换为字节数组,然后将字节数组转换为blob,然后再转换为base 64。或者将文件转换为字节数组并在附件字段中使用。
  • 上面是“Content-Transfer-Encoding: base64”,所以我只是假设字节数组是 Base64 ASCII 文本。我这边没有复杂的想法。
  • 我正在获取附加的图像,但它没有被打开,因为它说它在 windows 中已损坏。我尝试了以下,byte[] encoded = Base64.getEncoder().encode(fileContent) ;//文件内容为字节数组 String pngData = new String(encoded,StandardCharsets.US_ASCII"); pngData = pngData.replace("/", "_"); pngData = pngData.replace("+", "-" ); pngData = pngData.replace("=", "*");
  • Base64 有 3 种不同的类型,末尾的填充 (=) 也是可配置的。 Base64.getUrlEncoder() 使用 _- i.o. /+。而getMimeEncoder 可以将文本换行。字节数据是有效的 png 吗?

标签: java gmail-api


【解决方案1】:

带附件的草稿保存正确格式如下,

Content-Type: multipart/mixed; boundary="foo_bar_baz"
MIME-Version: 1.0
to: receiver@gmail.com
from: sender@gmail.com
subject: Subject Text

--foo_bar_baz
Content-Type: text/plain; charset="UTF-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

The actual message text goes here

--foo_bar_baz
Content-Type: image/jpeg
MIME-Version: 1.0
Content-Transfer-Encoding: 
Content-Disposition: attachment; filename="example.jpg"

VG86IGZvb0BleGFtcGxlLmNvbQ0KU3ViamVjdDpJZ25vcmUNCg0KdGVzdCBtYWlsIGJvZHkNCg==

--foo_bar_baz--

将上面的整个代码编码为base64,然后将其作为原始参数传递给gmail api。

【讨论】:

    猜你喜欢
    • 2014-08-17
    • 2012-05-28
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2017-05-01
    • 2014-12-11
    • 2020-04-27
    • 2019-08-27
    相关资源
    最近更新 更多