Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

Adding .jpg files to an email

2010-11-10
2013-04-25
  • Casey Harris
    Casey Harris
    2010-11-10

    Hello all,

    the code below is supposed to send a HTML response to a sender.

    There is supposed to be an image "error.jpg" sent back to the caller.

    The image that goes to the caller is damaged.

    Qustion: Does the code below show the correct way to attach an image to an email?

    Supposed to send a HTML response:  

        // reply error prepare
        vmime::ref<vmime::net::message> orgMsg = folder->getMessage(idx+1);
        folder->fetchMessage( orgMsg, vmime::net::folder::FETCH_FULL_HEADER );
        std::string replyAddress = orgMsg->getHeader()->From()->getValue()->generate();
        std::string replyError = std::string("ERROR: ");

        vmime::ref<vmime::message> reply = connection->getForward( idx+1, replyAddress, replyError );
       
        vmime::ref<vmime::bodyPart> body = vmime::create<vmime::bodyPart>();

        std::ifstream * fileStream = new std::ifstream("./file.jpg", std::ios_base::binary );
        vmime::ref<vmime::utility::inputStream> dataStream = vmime::create<vmime::utility::inputStreamPointerAdapter>(fileStream);
        vmime::ref<vmime::contentHandler> handler = vmime::create<vmime::streamContentHandler>(dataStream, 0);

        vmime::ref<vmime::htmlTextPart> bodyHtml = vmime::create<vmime::htmlTextPart>();
        const vmime::string id = bodyHtml->addObject( handler,
          vmime::mediaType( vmime::mediaTypes::IMAGE, vmime::mediaTypes::IMAGE_JPEG));
        bodyHtml->setText(vmime::create<vmime::stringContentHandler>(vmime::string("<img src=\"") + id + vmime::string("\">")));
        bodyHtml->generateIn( body, reply );
        // Change sequence of attach parts.
        body = reply->getBody()->getPartAt(0);
        reply->getBody()->appendPart( body );
        reply->getBody()->removePart(0);

        outConnection.connect();
        outConnection.sendMessage( reply );
        outConnection.disconnect();
        folder->deleteMessage( idx+1 );

    Regards.