Click here to Skip to main content
15,886,724 members
Articles / Productivity Apps and Services / Biztalk
Tip/Trick

Extract Email Body, Subject, Sender, Content Type and Attachment in BizTalk Pipeline

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
28 May 2020CPOL2 min read 6.2K   4  
Read Email in BizTalk Pipeline component
In this article we will demonstrate step by step instructions of how to extract email attachments in Base64 fromat, from POP3 adapter by using custom receive pipeline.

Introduction

You can have some customers that need to integrate with your integration middle-ware using POP3. So, They will send emails with multiple attachments and these attachments represent the messages that you need to process.

Using the code

To process email attachments through message level, we need to process them using pipeline component. To achive this, we need to implement custom receive pipeline and add it to decode part of receive pipeline. For now let's start our walk-though demonstration.

Create Custom Receive Pipeline

  1. Open visual studio and create new “Class Library” type project
  2. Add reference to assembly “Microsoft.BizTalk.Pipeline.dll”. You can find this assembly inside Microsoft Biztalk Server installation folder. For example, on my system this assembly was found insides folder “C:\Program Files (x86)\Microsoft BizTalk Server 20XX\
  3. Now add new code file (.cs file in case of Visual C# based project) to class library project. This code file contain all required functionality, code and implementation for custom disassembler component.
  4. Implement the following Code.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.BizTalk.Component.Interop;
    using Microsoft.BizTalk.Message.Interop;
    using System.IO;
    using System.Xml;
    
    
    namespace Email_to_XML_With_Attachment
    {
      [ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
      [ComponentCategory(CategoryTypes.CATID_Decoder)]
      [ComponentCategory(CategoryTypes.CATID_Encoder)]
      [System.Runtime.InteropServices.Guid("AE5942E8-8BEC-44EE-B147-E9394F281A8B")]
      public class EmailToXMLWithAttachment : IBaseComponent, IComponent, IPersistPropertyBag, IComponentUI
      {
        private string strNamespace = null;
    
        public string NamespaceUri
        {
          get { return strNamespace; }
          set { strNamespace = value; }
        }
    
        #region IBaseComponent Members
    
        public string Description
        {
          get { return "Transforms Email to Xml with Attachment"; }
        }
    
        public string Name
        {
          get { return "Email_To_Xml_With_Attachment"; }
        }
    
        public string Version
        {
          get { return "1.0"; }
        }
    
        #endregion
    
        #region IComponentUI Members
    
        public IntPtr Icon
        {
          get { return IntPtr.Zero; }
        }
    
        public System.Collections.IEnumerator Validate(object projectSystem)
        {
          return null;
        }
    
        #endregion
        #region IBaseMessage Execute
    
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
          IBaseMessagePart bodyPart = null;
    
          IBaseMessageContext context = pInMsg.Context;
    
    
          string originalDataString = String.Empty;
          bodyPart = pInMsg.BodyPart;
          Stream originalMessageStream = pInMsg.BodyPart.GetOriginalDataStream();
          StreamReader strReader = new StreamReader(originalMessageStream);
          originalDataString = strReader.ReadToEnd();
    
          originalDataString = originalDataString.Replace("&", "&");
          originalDataString = originalDataString.Replace("<", "&lt;");
          originalDataString = originalDataString.Replace(">", "&gt;");
    
          XmlDocument originalMessageDoc = new XmlDocument();
          string strMsg = string.Empty;
          string emailSub = string.Empty;
          string emailFrom = string.Empty;
          string emailTo = string.Empty;
          string partName = String.Empty;
          string _contentType = String.Empty;
          string baseAttach64 = String.Empty;
          string strAttchment = String.Empty;
    
    
          emailSub = pInMsg.Context.Read("Subject", "http://schemas.microsoft.com/BizTalk/2003/pop3-properties").ToString();
          emailFrom = pInMsg.Context.Read("From", "http://schemas.microsoft.com/BizTalk/2003/pop3-properties").ToString();
          emailTo = pInMsg.Context.Read("To", "http://schemas.microsoft.com/BizTalk/2003/pop3-properties").ToString();
    
          emailFrom = emailFrom.Replace("<", "&lt;");
          emailFrom = emailFrom.Replace(">", "&gt;");
          emailTo = emailTo.Replace("<", "&lt;");
          emailTo = emailTo.Replace(">", "&gt;");
          emailSub = emailSub.Replace("&", "&amp;");
          emailSub = emailSub.Replace("<", "&lt;");
          emailSub = emailSub.Replace(">", "&gt;");
    
          for (int i = 1; i < pInMsg.PartCount; i++)
          {
            string strAttach = String.Empty;
            IBaseMessagePart _partAttachment = pInMsg.GetPartByIndex(i, out partName);
            _contentType = _partAttachment.ContentType;
            Stream _attachmentStream = _partAttachment.GetOriginalDataStream();
            StreamReader strmAttach = new StreamReader(_attachmentStream);
             
            var memoryStream = new MemoryStream();
            strmAttach.BaseStream.CopyTo(memoryStream);
            byte[] bytes = memoryStream.ToArray();
    
             baseAttach64 = Convert.ToBase64String(bytes);
            strAttach = ("<Attachment>"
                      + "<contentType>" + _contentType + "</contentType>"
                      + "<contentName>" + partName + "</contentName>"
                      + "<content>" + baseAttach64 + "</content>"
                    + "</Attachment>");
    
            strAttchment = strAttchment + strAttach;
    
          }
    
    
          strMsg =
            "<ns0:TicketInfo xmlns:ns0=\"" + NamespaceUri + "\">"
            + "<subject>" + emailSub + "</subject>"
            + "<body>" 
               + originalDataString 
            + "</body>"
            + "<Attachments>"
               + strAttchment
            + "</Attachments>"
            + "<sender>" + emailFrom + "</sender>"
            + "<recipient>" + emailTo + "</recipient>"
            + "</ns0:TicketInfo>";
    
    
          MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(strMsg));
          bodyPart.Data = memStream;
    
          return pInMsg;
        }
        #endregion
    
        #region IPersistPropertyBag Members
    
        public void InitNew()
        {
    
        }
    
        public void GetClassID(out Guid classID)
        {
          classID = new Guid("AE5942E8-8BEC-44EE-B147-E9394F281A8B");
        }
    
    
        public void Load(IPropertyBag propertyBag, int errorLog)
        {
          try
          {
            object value;
            propertyBag.Read("NamespaceUri", out value, 0);
            if (value != null)
              strNamespace = (string)value;
          }
          catch (Exception)
          {
            strNamespace = null;
          }
    
        }
        public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
        {
    
          object value;
    
          value = strNamespace;
          propertyBag.Write("NamespaceUri", ref value);
    
        }
        #endregion
      }
    }
  5. To make this custom component public for use within visual studio, copy/past the output dll projet to:

    Biztalk Server Install Path\Pipeline Components. otherwise, to be able to debug our component, we need to GAC the dll.

    Steps to create custom pipeline:

  6. Open visual studio
  7. Create new empty BizTalk project and then add receive pipeline to the project.
  8. Open pipeline file (.btp file) and right click on “Toolbar” and select “Choose Item” option, Go to BizTalk Component tab and select your custom component from the list of available components. This will add component to the toolbar.
  9. Now drag your custom component from the toolbar and drop it in the “Decode” stage of the pipeline.
  10. Now deploy your solution and your custom pipeline should appear in “Pipeline” folder/section of BizTalk Administrator and ready to use
  11. Now go to admin Console and configure aa valid namespace in pipeline. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --