Wednesday, July 21, 2004

Processing attachments in a embedded email message

I had a question from someone today about how to process the attachments on a embedded email (basically when you get an email that has another email attached to it which has attachments). The basic code to process a set of attachments on a message in Ex2k look like this

set msg = createobject("cdo.message")
msg.datasource.open "file://./backofficestorage/domain.com/MBX/user/Inbox/Mess.EML"
set objattachments = msg.attachments
for each objattachment in objattachments
     objattachment.savetofile "d:\temp\" & objattachment.filename
next


If you have an email with a embedded email as an attachment this embedded email will appear in the attachment well of the the other email as content type message/rfc822 but the filename will be blank and the above code would fail to execute at this step. To process these type of messages you need to open the embedded message from the bodypart and then process the attachments on this message. The other problem now is that the depth of embedded email could be greater then just one so this is when some sort of function you can call recursively is really needed within your code. Embedded email extraction is covered in the Exchange SDK here . Here's some code to extract multiple depth attachments in a multiple embedded message.

set msg = createobject("cdo.message")
msg.datasource.open "file://./backofficestorage/domain.com/MBX/user/Inbox/Mess.EML"
set objattachments = msg.attachments
for each objattachment in objattachments
if objAttachment.ContentMediaType = "message/rfc822" then
procattach(objattachment)
else
objattachment.savetofile "d:\temp\" & objattachment.filename
end if
next
set msg = nothing

function procattach(objattachment)
set msg1 = createobject("cdo.message")
msg1.datasource.OpenObject objattachment, "ibodypart"
set objattachments1 = msg1.attachments
for each objattachment1 in objattachments1
if objAttachment1.ContentMediaType = "message/rfc822" then
procattach(objattachment1)
else
objattachment1.savetofile "d:\temp\" & objattachment1.filename
end if
next
set msg1 = nothing
end function