Gmail Api send text and html in one mail

2019-08-15 02:12发布

问题:

Mail sending either text or html works perfectly fine, but when i send them both in single mail, html comes as an attachment named "noname.html", which contains html.

I have read other related questions on this topic, but couldn't find what is possibly wrong.

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--`

回答1:

You want to send both HTML body and text body using gmail API. If my understanding is correct, how about this modification?

From :

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

To :

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

Note :

  • Using multipart/alternative, both parts of Content-type: text/plain; charset="UTF-8" and Content-type: text/html; charset="UTF-8" can be sent.

Reference :

  • https://en.wikipedia.org/wiki/MIME#Content-Type

In my environment, I could confirm that your request body which was modified to multipart/alternative worked. If this didn't work on your environment, I'm sorry.

Edit :

In order to send a text body, a HTML body and an attachment file of HTML as one email, the structure of request body can be created as follows.

  • multipart/mixed
    • multipart/alternative
      • text/plain
      • text/html
    • text/html (Attachment file)

Sample request body :

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--

References :

  • https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
  • http://qcode.co.uk/post/70