C++ にて VMime を使って HTMLメールを作成する

C++ にて VMime を使って メールを送信する
の続きです。

HTML メールの仕様

RFC 2046、 RFC2854 に規定はあるが、 決め事は多くない。

RFC 2046
Multipurpose Internet Mail Extensions
(MIME) Part Two:
Media Types
http://www.t-net.ne.jp/~cyfis/rfc/mime/rfc2046_ja-1.html

RFC2854
The 'text/html' Media Type
http://www.cam.hi-ho.ne.jp/mendoxi/rfc/rfc2854j.html

慣例として以下のようにしている。

下記のように、multipart の中に plain の本文とHTMLのパートを置く。

Content-Type: multipart/alternative

Content-Type: text/plain
本文のデータ

Content-Type: text/html
HTML のデータ

HTML をどう扱うかは、メールアプリにより異なります。 webブラウザのように多様な表示ができるわけではない。 HTMLデータは、古典的なHTMLタグを使って記述するのが無難です。

参考 HTMLメールとテキストメールの違いとは https://ms.repica.jp/column/20190123_faq_htmlmail_textmail/#:~:text=%E3%81%93%E3%81%AEHTML%E3%81%A7%E4%BD%9C%E6%88%90%E3%81%95%E3%82%8C,%E4%BD%9C%E3%82%8B%E3%81%93%E3%81%A8%E3%81%8C%E3%81%A7%E3%81%8D%E3%81%BE%E3%81%99%E3%80%82

参考 HTMLメール作成で調べたことまとめ
https://qiita.com/ta-ke-no-bu/items/675130afd1ecc09e38b4

HTML メールを作成する

vmime::htmlTextPart を使用する

htmlTextPart Class Reference https://www.vmime.org/public/documentation/doxygen/classvmime_1_1htmlTextPart.html

下記のように記述する

vmime::messageBuilder mb;

 // TextPart
std::string body = "";
mb.getTextPart()->setText(
vmime::make_shared <vmime::stringContentHandler>(body) );

// Set the content-type to "text/html"
    mb.constructTextPart(
    vmime::mediaType(
    vmime::mediaTypes::TEXT,
    vmime::mediaTypes::TEXT_HTML
    )
    );

    vmime::htmlTextPart& textPart =
        *vmime::dynamicCast <vmime::htmlTextPart>(mb.getTextPart());

    // HTML part
    textPart.setText( 
        vmime::make_shared <vmime::stringContentHandler>(
            html )
    );

// plain part
    textPart.setPlainText(
        vmime::make_shared <vmime::stringContentHandler>(
                plain )
    );

HTML の記述

HTMLデータは、下記のように記述する。

  • DOCTYPE から始める。
  • body部は table で記述する。
  • 古典的なHTMLタグを使用する。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html  xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
  <meta name="viewport" content="width=device-width" />
  <title>VMime</title>
</head>
<body>
<table>
<tr>
<td width="615" align="center" valign="top" bgcolor="#2F5597" style="padding: 10px 0; font-size:18px; color:#ffffff; line-height:1.5;">
Welcome to VMime
</td>
</tr>
<tr>
<td align="center" valign="top">
<center>
<b>MIME and Mail Library for C++</b>
</center>
</td>
</tr>
<tr>
<td align="center" valign="top">
<center>
<br/>
<a href="https://www.vmime.org/">more detail</a>
</center>
</td>
</tr>
</table>
</body>
</html>

作成したメールをメールアプリの Thnderbird で見るとこうなる。

f:id:ken_ohwada:20210121140907p:plain
mail_html_file

注:
img タグでリモート画像を指定しても、
Thnderbird はブロックして、表示されない。

全体のコードは、githubに公開した。
https://github.com/ohwada/MAC_cpp_Samples/tree/master/vmime/create