C++ にて VMime を使って ファイルからメールを読む
の続きです。
VMime の 日本語サポート
VMime のデフォルトの文字セットは 7ビットASCIIです。 日本語など非ASCIIテキストにも対応している。
下記は、VMime Book に掲載されている例
4.7 文字セットおよび変換 https://ken-ohwada.hatenadiary.org/entry/2020/12/29/122841
受信したメールの本文を UTF-8 に変換する例
vmime:::shared ptr <vmime: : message> msg; // we have a message // Obtain the content handler first vmime::shared ptr <vmime::body> body = msg−>getBody(); vmime::shared ptr <const vmime::contentHandler> cth = body−>getContents(); // Then, extract and convert the contents vmime::utility::outputStreamAdapter out(std::cout); vmime::utility::charsetFilteredOutputStream fout (/∗ source charset ∗/ body−>getCharset(), /∗ dest charset ∗/ vmime::charset("utf−8"), /∗ dest stream ∗/ out); cth−>extract(fout); fout.flush(); // Very important!
この例のままだと、下記のコンパイルエラーになる。
vmime::utility::charsetFilteredOutputStream' is an abstract class
下記のように、変更する
vmime::string str_out; vmime::utility::outputStreamStringAdapter out(str_out); cth->extract(out); vmime::string src( str_out ); // source charset vmime::charset src_charset = body->getCharset(); // dest charset vmime::charset dst_charset(vmime::charsets::UTF_8); vmime::string dst; vmime::charset::convert( src, dst, src_charset, dst_charset ); cout << dst << endl;
ヘッダーフィールド
下記は、VMime Book に掲載されている例
4.8 ヘッダーフィールドの非ASCIIテキスト
https://ken-ohwada.hatenadiary.org/entry/2020/12/29/123018
受信したメールの題名 (Subject) を UTF-8 に変換する例
vmime::shared ptr <vmime::message> msg; // we have a message vmime::text subject = msg−>getHeader()->Subject()->getValue(); const vmime::string subjectText = subject.getConvertedText(vmime::charset("utf−8") ); // ’subjectText’ now contains the subject in UTF−8 encoding
全体のコードは、githubに公開した。
https://github.com/ohwada/MAC_cpp_Samples/tree/master/vmime/read