Recently we had a requirement to send email from BizTalk with a number of attachments. This sounds like an easy thing to do, until we realised the number of attachments required would vary at runtime. It could be anywhere from zero, to lots.
In trying to work out the best method to achieve this, I first tried manually creating a multipart MIME message that contained explicit boundaries, and the appropriate content types. It didn’t seem to work reliably so after a bit of searching I found this article which used the idea of directly adding XLANGPart to the main XLANG email message.
One quick helper class later and it was all working:
public void AttachPartToMessage(XLANGMessage message, string partContent, string partFileName)
{
byte[] contentBuffer = UTF8Encoding.Default.GetBytes(partContent);
MemoryStream partStream = new MemoryStream(contentBuffer, 0, contentBuffer.Length, true, true);
string partName = Guid.NewGuid().ToString().Substring(0, 5);
message.AddPart(partStream, partName);
//derive the content type from the filename extension
string contentType = GetContentType(Path.GetExtension(partFileName).Replace(".", ""));
//set filename and content type for attachment
XLANGPart part = message[partName];
part.SetPartProperty(typeof(MIME.FileName), partFileName);
part.SetPartProperty(typeof(ContentType), contentType);
}
This can be used from the orchestration as follows (note the main XLANG message to which you are adding the parts, must be multipart)
MessageHelper.AttachPartToMessage(EmailMsg, "<test>this is attachment one</test>","Sample.xml");
MessageHelper.AttachPartToMessage(EmailMsg, "<html><body><i>Hello World<i></body></html>", "Test.html");
MessageHelper.AttachPartToMessage(EmailMsg, InboundMsg.OuterXml, "InboundMsg.xml");
The resulting message shows up properly in Outlook :-)
Cheers!
0 comments:
Post a Comment