Your recv code is okay. The algorithm you need: every time your recv() call returns with a piece of data you append it to your buffer - you commented the place where you would otherwise call your appender function. This appender func should do a minimal parsing on the mime data - it should be able to detect if the whole mime message has arrived and in this case you should break out of your recv loop and close the connection without performing any more recv() calls because that would result your application to hang up if the other side doesn't close the connection immediately after sending the full data. This is the same problem as with http clients that use blocking sockets like you, and the solution is also the same:
If you are not familiar with mime encoding, its a relatively simple to write a minimal "parser" that detects the end of the data without parsing it in detail. Take a look at the multipart mime message example here:
http://en.wikipedia.org/wiki/MIME#Multipart_messages[
^]
That is a "multipart/mixed" message not a "multipart/related" but it doesn't matter from your point of view because detecting the end of the mime data will be the same basically for each "multipart/something" message.
In the example the parts of the mime message are separated by the "--frontier" separator, and the whole multipart message is finished with the "--frontier--". You can easily write a mime parser that interprets the header of the multipart message, finds out the boundary (that is "frontier" in the example, and then you are ready to go and search for the finishing "--your_boundary_goes_here--" line. The boundary marks are always on a new line so its easy to go with the parsing line-by-line. You don't even have to care about the contents of the individual parts of the multipart message. Mime has hierarchy, each part can contain another multipart or whatever kind of mime block but those use different separators than the root message so you don't have to deal with those at all.