Search code examples
c++mime

How to create new GMimeMessage from string?


In my project i use libgmime for MIME types. I'm trying to create new GMimeMessage using std::string as a body. According to docs it can be done using GMimeStream and GMimeDataWrapper for preparing data, and then creating GMimePart from this data to be set as MIME part of new message. The code:

std::string body = "some test data";
GMimeMessage* message = g_mime_message_new(FALSE);
//set header
g_mime_object_set_header((GMimeObject *) message, name.c_str()), value.c_str();
//create stream and write data into it.
GMimeStream* stream;
g_mime_stream_construct(stream, 0, body.length());
g_mime_stream_write_string(stream, body.c_str());
GMimeDataWrapper* wrapper = g_mime_data_wrapper_new_with_stream(stream,  GMIME_CONTENT_ENCODING_DEFAULT);
//create GMimePart to be set as mime part of GMimeMessage
GMimePart* mime_part = g_mime_part_new();
g_mime_part_set_content_object(mime_part, wrapper);

g_mime_message_set_mime_part(message, (GMimeObject *) mime_part);

When i try to create message in this way, i get segfault here:

g_mime_stream_write_string(stream, body.c_str());

Maybe i'm using wrong method of message creation... What's the right way it can be done?


Solution

  • You have bad initialization GMimeStream *stream. Need:

    GMimeStream *stream;
    
    /* initialize GMime */
    g_mime_init (0);
    
    /* create a stream around stdout */
    stream = g_mime_stream_mem_new_with_buffer(body_part.c_str(), body_part.length()); 
    

    See doc: http://spruce.sourceforge.net/gmime/tutorial/x49.html And sample: http://fossies.org/linux/gmime/examples/basic-example.c