C++ にて VMime を使って メールを送信する
の続きです。
メールをファイルから読む
下記は、VMime Book に掲載されている例
5.1 メッセージの解析
https://ken-ohwada.hatenadiary.org/entry/2020/12/30/160715
ファイルからメールを読んで解析する例
// Read data from file std::ifstream file; file.open("hello.eml", std::ios::in | std::ios::binary); vmime::utility::inputStreamAdapter is(file); vmime::string data; vmime::utility::outputStreamStringAdapter os(data); vmime::utility::bufferedStreamCopy(is , os); // Actually parse the message vmime::shared_ptr <vmime::message> msg = vmime::make_shared<vmime::message>(); msg->parse(data); vmime::shared_ptr <vmime::header> hdr = msg->getHeader(); vmime::shared_ptr <vmime::body> bdy = msg->getBody(); // Now, you can extract some of its components vmime::charset ch(vmime::charsets::UTF_8); std::cout << " The subject of the message is : " << hdr->Subject()->getValue<vmime::text>()->getConvertedText(ch) << std::endl << " It was sent by: " << hdr->From()->getValue<vmime::mailbox>()->getName().getConvertedText(ch) << "( email: " << hdr->From()->getValue<vmime::mailbox>()->getEmail() << " )" << std::endl;
例のままだと、下記のエラーになる。
read_mail_hello.cpp:62:1: error: invalid operands to binary expression ('basic_ostream<char, std::__1::char_traits
>' and 'const vmime::emailAddress') << hdr->From()->getValue<vmime::mailbox>()->getEmail()
下記のように toString() を追加すればよい。
hdr->From()->getValue<vmime::mailbox>()->getEmail().toString()
本文を表示する
上記の例では、本文(body)が表示されない。
下記を追加する。
vmime::utility::outputStreamStringAdapter out(std::cout); vmime::shared_ptr<const vmime::contentHandler> cts = body->getContents(); cts->extract(out);
全体のコードは、githubに公開した。
https://github.com/ohwada/MAC_cpp_Samples/tree/master/vmime/read