首页 > 解决方案 > Gmail API:在一封邮件中发送文本和 HTML

问题描述

发送文本或 HTML 的邮件工作得非常好,但是当我将它们发送到单个邮件中时,HTML 以一个名为“noname.html”的附件的形式出现,其中包含 HTML。

我已阅读有关此主题的其他相关问题,但找不到可能的问题。

MIME-Version: 1.0
From: sender@gmail.com
To: receiver@gmail.com
Subject: test
Content-type: multipart/mixed; boundary="012boundary"

--012boundary
Content-type: text/plain; charset="UTF-8"

Hello plain text!

--012boundary
Content-type: text/html; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

<b>Hello html</b>
--012boundary--`

标签: gmailgmail-api

解决方案


您想使用 gmail API 发送 HTML 正文和文本正文。如果我的理解是正确的,那么这个修改呢?

从 :

Content-type: multipart/mixed; boundary="012boundary"

至 :

Content-type: multipart/alternative; boundary="012boundary"

笔记 :

  • 使用,和multipart/alternative的两个部分都可以发送。Content-type: text/plain; charset="UTF-8"Content-type: text/html; charset="UTF-8"

参考 :

在我的环境中,我可以确认您的请求正文已修改为multipart/alternative有效。如果这对您的环境不起作用,我很抱歉。

编辑 :

为了将文本正文、HTML 正文和 HTML 的附件文件作为一封电子邮件发送,请求正文的结构可以创建如下。

  • 多部分/混合
    • 多部分/替代
      • 文本/纯文本
      • 文本/html
    • 文本/html(附件文件)

示例请求正文:

MIME-Version: 1.0
From: sender@gmail.com
To: receiver@gmail.com
Subject: test
Content-Type: multipart/mixed; boundary=012boundary01

--012boundary01
Content-Type: multipart/alternative; boundary=012boundary02

--012boundary02
Content-type: text/plain; charset=UTF-8

Hello plain text!

--012boundary02
Content-type: text/html; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

<b>Hello html</b>

--012boundary02--
--012boundary01
Content-type: text/html; charset=UTF-8
Content-Disposition: attachment; filename="sample.html"
Content-Transfer-Encoding: quoted-printable

<b>HTML sample attachment file</b>
--012boundary01--

参考 :


推荐阅读