public static bool IsInitiationMessage(EmailMessage message)
        {
            HeaderList headers = message.MimeDocument.RootPart.Headers;
            Header     header  = headers.FindFirst("X-MS-Exchange-Organization-Approval-Initiator");
            Header     header2 = headers.FindFirst("X-MS-Exchange-Organization-Approval-Allowed-Decision-Makers");

            return(header != null && header2 != null);
        }
Example #2
0
        private ApprovalEngine.ApprovalProcessResults HandleInitiationMessage(InitiationMessage initiationMessage)
        {
            if (initiationMessage.IsMapiInitiator)
            {
                if (!this.sender.Equals(this.recipient))
                {
                    return(ApprovalEngine.ApprovalProcessResults.Invalid);
                }
            }
            else if (string.Equals("ModeratedTransport", initiationMessage.ApprovalInitiator, StringComparison.OrdinalIgnoreCase))
            {
                this.messageItem[MessageItemSchema.ApprovalApplicationId] = 1;
                HeaderList headers    = this.message.MimeDocument.RootPart.Headers;
                TextHeader textHeader = headers.FindFirst("X-MS-Exchange-Organization-Moderation-Data") as TextHeader;
                string     value;
                if (textHeader != null && textHeader.TryGetValue(out value) && !string.IsNullOrEmpty(value))
                {
                    this.messageItem[MessageItemSchema.ApprovalApplicationData] = value;
                }
                this.StampModeratedTransportExpiry();
            }
            if (initiationMessage.DecisionMakers == null)
            {
                return(ApprovalEngine.ApprovalProcessResults.Invalid);
            }
            if (InitiationProcessor.CheckDuplicateInitiationAndUpdateIdIfNecessary(this.messageItem))
            {
                return(ApprovalEngine.ApprovalProcessResults.DuplicateInitiation);
            }
            InitiationProcessor initiationProcessor = new InitiationProcessor(this.mbxTransportMailItem, initiationMessage, this.messageItem, this.requestCreate, this.recipient);

            return(initiationProcessor.PrepareApprovalRequestData());
        }
        private void OnEndOfDataHandler(ReceiveMessageEventSource source, EndOfDataEventArgs e)
        {
            string[] addrs;
            //hash code is not guaranteed to be unique. Add time to fix uniqueness
            string itemId = e.MailItem.GetHashCode().ToString() + e.MailItem.FromAddress.ToString();

            if (this.origToMapping.TryGetValue(itemId, out addrs))
            {
                this.origToMapping.Remove(itemId);
                if (this.databaseConnector != null)
                {
                    this.databaseConnector.LogCatch(addrs[0], addrs[1], e.MailItem.Message.Subject, e.MailItem.Message.MessageId);
                }

                //Add / update orig to header
                if (CatchAllFactory.AppSettings.AddOrigToHeader)
                {
                    MimeDocument mdMimeDoc    = e.MailItem.Message.MimeDocument;
                    HeaderList   hlHeaderlist = mdMimeDoc.RootPart.Headers;
                    Header       origToHeader = hlHeaderlist.FindFirst("X-OrigTo");

                    if (origToHeader == null)
                    {
                        MimeNode   lhLasterHeader = hlHeaderlist.LastChild;
                        TextHeader nhNewHeader    = new TextHeader("X-OrigTo", addrs[0]);
                        hlHeaderlist.InsertBefore(nhNewHeader, lhLasterHeader);
                    }
                    else
                    {
                        origToHeader.Value += ", " + addrs[0];
                    }
                }
            }
        }
        private TransportMailItem CreateMailItem()
        {
            TransportMailItem transportMailItem = TransportMailItem.NewSideEffectMailItem(this.context.MbxTransportMailItem, this.context.RecipientCache.OrganizationId, LatencyComponent.MailboxRules, MailDirectionality.Originating, this.context.MbxTransportMailItem.ExternalOrganizationId);

            base.CopyContentTo(transportMailItem);
            base.DecorateMessage(transportMailItem);
            base.ApplySecurityAttributesTo(transportMailItem);
            transportMailItem.PrioritizationReason = this.context.PrioritizationReason;
            transportMailItem.Priority             = this.context.Priority;
            ClassificationUtils.PromoteStoreClassifications(transportMailItem.RootPart.Headers);
            SubmissionItemUtils.PatchQuarantineSender(transportMailItem, base.QuarantineOriginalSender);
            HeaderList headers = transportMailItem.RootPart.Headers;

            if (headers.FindFirst(HeaderId.MessageId) == null)
            {
                headers.AppendChild(new AsciiTextHeader("Message-Id", string.Concat(new string[]
                {
                    "<",
                    Guid.NewGuid().ToString("N"),
                    "@",
                    this.SourceServerFqdn,
                    ">"
                })));
            }
            MimeInternalHelpers.CopyHeaderBetweenList(this.context.RootPart.Headers, headers, "X-MS-Exchange-Moderation-Loop");
            transportMailItem.UpdateCachedHeaders();
            return(transportMailItem);
        }
Example #5
0
        private void SendNotifications(RoutingAddress from, RoutingAddress recipient, MbxTransportMailItem rmi, string threadIndex, string threadTopic, string existingDecisionMakerAddress, ApprovalStatus?existingApprovalStatus, ExDateTime?existingDecisionTime)
        {
            HeaderList headers = rmi.RootPart.Headers;
            Header     acceptLanguageHeader     = headers.FindFirst("Accept-Language");
            Header     contentLanguageHeader    = headers.FindFirst(HeaderId.ContentLanguage);
            string     decisionMakerDisplayName = existingDecisionMakerAddress;
            bool?      flag = null;

            if (existingApprovalStatus != null)
            {
                if ((existingApprovalStatus.Value & ApprovalStatus.Approved) == ApprovalStatus.Approved)
                {
                    flag = new bool?(true);
                }
                else if ((existingApprovalStatus.Value & ApprovalStatus.Rejected) == ApprovalStatus.Rejected)
                {
                    flag = new bool?(false);
                }
            }
            if (!string.IsNullOrEmpty(existingDecisionMakerAddress))
            {
                ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    IRecipientSession recipientSession = ApprovalProcessor.CreateRecipientSessionFromSmtpAddress(existingDecisionMakerAddress);
                    ADRawEntry adrawEntry = recipientSession.FindByProxyAddress(new SmtpProxyAddress(existingDecisionMakerAddress, true), ApprovalProcessingAgent.DisplayNameProperty);
                    if (adrawEntry != null)
                    {
                        string text = (string)adrawEntry[ADRecipientSchema.DisplayName];
                        if (!string.IsNullOrEmpty(text))
                        {
                            decisionMakerDisplayName = text;
                        }
                    }
                }, 1);
            }
            ApprovalProcessingAgent.diag.TraceDebug <bool?, string>(0L, "Generating conflict notification. Decision='{0}', DecisionMaker='{1}'", flag, decisionMakerDisplayName);
            EmailMessage emailMessage = NotificationGenerator.GenerateDecisionNotTakenNotification(from, recipient, rmi.Subject, threadIndex, threadTopic, decisionMakerDisplayName, flag, existingDecisionTime, acceptLanguageHeader, contentLanguageHeader, rmi.TransportSettings.InternalDsnDefaultLanguage);

            if (emailMessage != null)
            {
                this.server.SubmitMessage(rmi, emailMessage, rmi.OrganizationId, rmi.ExternalOrganizationId, false);
            }
        }
Example #6
0
        internal static string GetProperty(HeaderList mimeHeaders, string name)
        {
            Header header = mimeHeaders.FindFirst(name);

            if (header == null || header.Value == null)
            {
                return(null);
            }
            return(header.Value);
        }
Example #7
0
            public override bool FilterHeaderList(HeaderList headerList, Stream stream)
            {
                Header header = headerList.FindFirst(HeaderId.ContentTransferEncoding);

                if (header != null)
                {
                    ContentTransferEncoding encodingType = MimePart.GetEncodingType(header.FirstRawToken);
                    if (encodingType == ContentTransferEncoding.EightBit || encodingType == ContentTransferEncoding.Binary)
                    {
                        ContentTypeHeader typeHeader = headerList.FindFirst(HeaderId.ContentType) as ContentTypeHeader;
                        bool flag;
                        bool flag2;
                        EightToSevenBitConverter.Analyse(typeHeader, out this.embedded, out flag, out flag2);
                        for (MimeNode mimeNode = headerList.FirstChild; mimeNode != null; mimeNode = mimeNode.NextSibling)
                        {
                            if (HeaderId.ContentTransferEncoding == (mimeNode as Header).HeaderId)
                            {
                                if (flag || this.embedded)
                                {
                                    this.encoder = null;
                                }
                                else if (flag2)
                                {
                                    stream.Write(EightToSevenBitConverter.CteQP, 0, EightToSevenBitConverter.CteQP.Length);
                                    this.encoder = new QPEncoder();
                                }
                                else
                                {
                                    stream.Write(EightToSevenBitConverter.CteBase64, 0, EightToSevenBitConverter.CteBase64.Length);
                                    this.encoder = new Base64Encoder();
                                }
                            }
                            else
                            {
                                mimeNode.WriteTo(stream);
                            }
                        }
                        stream.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                        return(true);
                    }
                }
                return(false);
            }
        private static Guid GetGal(HeaderList headers)
        {
            ArgumentValidator.ThrowIfNull("headers", headers);
            Header header = headers.FindFirst("X-MS-Exchange-Forest-GAL-Scope");

            if (header != null)
            {
                return(StoreDriverDelivery.GetHeaderValueAsGuid(header));
            }
            return(Guid.Empty);
        }
Example #9
0
        private void CacheInstanceId(HeaderList headers, StoreId instanceCalendarItemId)
        {
            Header header = headers.FindFirst("X-MS-Exchange-Calendar-Series-Instance-Calendar-Item-Id");

            if (header == null)
            {
                header = Header.Create("X-MS-Exchange-Calendar-Series-Instance-Calendar-Item-Id");
                headers.AppendChild(header);
            }
            header.Value = StoreId.GetStoreObjectId(instanceCalendarItemId).ToBase64String();
        }
        private static Guid GetAddressBookPolicy(HeaderList headers)
        {
            ArgumentValidator.ThrowIfNull("headers", headers);
            Header header = headers.FindFirst("X-MS-Exchange-ABP-GUID");

            if (header != null)
            {
                return(StoreDriverDelivery.GetHeaderValueAsGuid(header));
            }
            return(Guid.Empty);
        }
Example #11
0
            public static MeetingSeriesMessageOrderingAgent.SeriesHeadersData FromHeaderList(HeaderList headers, Guid messageId)
            {
                TextHeader textHeader  = headers.FindFirst("X-MS-Exchange-Calendar-Series-Id") as TextHeader;
                TextHeader textHeader2 = headers.FindFirst("X-MS-Exchange-Calendar-Series-Sequence-Number") as TextHeader;
                TextHeader textHeader3 = headers.FindFirst("X-MS-Exchange-Calendar-Series-Instance-Id") as TextHeader;
                TextHeader textHeader4 = headers.FindFirst("X-MS-Exchange-Calendar-Series-Master-Id") as TextHeader;
                TextHeader textHeader5 = headers.FindFirst("X-MS-Exchange-Calendar-Series-Instance-Unparked") as TextHeader;

                MeetingSeriesMessageOrderingAgent.SeriesHeadersData result = new MeetingSeriesMessageOrderingAgent.SeriesHeadersData
                {
                    SeriesId = ((textHeader != null) ? textHeader.Value : null)
                };
                MeetingSeriesMessageOrderingAgent.tracer.TraceDebug <string>(0L, "SeriesId: {0}", result.SeriesId ?? string.Empty);
                int num;

                if (textHeader2 != null && int.TryParse(textHeader2.Value, out num))
                {
                    result.SeriesSequenceNumber = num;
                    MeetingSeriesMessageOrderingAgent.tracer.TraceDebug <int>(0L, "SeriesSequenceNumber: {0}", num);
                }
                byte[] instanceGoid;
                if (textHeader3 != null && MeetingSeriesMessageOrderingAgent.SeriesHeadersData.TryParseGoid(textHeader3.Value, out instanceGoid))
                {
                    result.InstanceGoid = instanceGoid;
                    MeetingSeriesMessageOrderingAgent.tracer.TraceDebug <string>(0L, "InstanceGoid: {0}", textHeader3.Value);
                }
                byte[] masterGoid;
                if (textHeader4 != null && MeetingSeriesMessageOrderingAgent.SeriesHeadersData.TryParseGoid(textHeader4.Value, out masterGoid))
                {
                    result.MasterGoid = masterGoid;
                    MeetingSeriesMessageOrderingAgent.tracer.TraceDebug <string>(0L, "MasterGoid: {0}", textHeader4.Value);
                }
                if (textHeader5 != null && !string.IsNullOrEmpty(textHeader5.Value))
                {
                    result.UnparkedMessage = (textHeader5.Value == messageId.ToString());
                    MeetingSeriesMessageOrderingAgent.tracer.TraceDebug <string, Guid>(0L, "UnparkedMessageId: {0}, processed message id: {1}", textHeader5.Value, messageId);
                }
                return(result);
            }
Example #12
0
        public static MessagingPoliciesUtils.JournalVersion CheckJournalReportVersion(HeaderList headerList)
        {
            if (headerList == null)
            {
                return(MessagingPoliciesUtils.JournalVersion.None);
            }
            Header header = headerList.FindFirst("X-MS-Journal-Report");

            if (header != null)
            {
                return(MessagingPoliciesUtils.JournalVersion.Exchange2007);
            }
            header = headerList.FindFirst("Content-Identifier");
            if (header != null && !string.IsNullOrEmpty(header.Value) && string.Compare(header.Value, "exjournalreport", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return(MessagingPoliciesUtils.JournalVersion.Exchange2003);
            }
            header = headerList.FindFirst("Content-Identifer");
            if (header != null && !string.IsNullOrEmpty(header.Value) && string.Compare(header.Value, "exjournalreport", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return(MessagingPoliciesUtils.JournalVersion.Exchange2003);
            }
            return(MessagingPoliciesUtils.JournalVersion.None);
        }
Example #13
0
        public void DecorateMessage(TransportMailItem message)
        {
            message.HeloDomain           = ConfigurationProvider.GetDefaultDomainName();
            message.ReceiveConnectorName = "FromLocal";
            message.RefreshMimeSize();
            long       mimeSize = message.MimeSize;
            HeaderList headers  = message.RootPart.Headers;

            if (!(headers.FindFirst(HeaderId.Date) is DateHeader))
            {
                DateHeader newChild = new DateHeader("Date", DateTime.UtcNow.ToLocalTime());
                headers.AppendChild(newChild);
            }
            headers.RemoveAll(HeaderId.Received);
            DateHeader     dateHeader = new DateHeader("Date", DateTime.UtcNow.ToLocalTime());
            string         value      = dateHeader.Value;
            ReceivedHeader newChild2  = new ReceivedHeader(this.SourceServerFqdn, SubmissionItemBase.FormatIPAddress(this.SourceServerNetworkAddress), this.LocalIP.HostName, this.ReceivedHeaderTcpInfo, null, this.mailProtocol, SubmissionItemBase.serverVersion, null, value);

            headers.PrependChild(newChild2);
            message.ExtendedProperties.SetValue <bool>("Microsoft.Exchange.Transport.ElcJournalReport", this.IsElcJournalReport);
            if (this.IsMapiAdminSubmission)
            {
                headers.AppendChild(new AsciiTextHeader("X-MS-Exchange-Organization-Mapi-Admin-Submission", string.Empty));
            }
            if (this.IsDlExpansionProhibited)
            {
                headers.AppendChild(new AsciiTextHeader("X-MS-Exchange-Organization-DL-Expansion-Prohibited", string.Empty));
            }
            headers.AppendChild(new AsciiTextHeader("X-MS-Exchange-Organization-Processed-By-MBTSubmission", string.Empty));
            if (ConfigurationProvider.GetForwardingProhibitedFeatureStatus() && this.IsAltRecipientProhibited)
            {
                headers.AppendChild(new AsciiTextHeader("X-MS-Exchange-Organization-Alt-Recipient-Prohibited", string.Empty));
            }
            headers.RemoveAll("X-MS-Exchange-Organization-OriginalSize");
            headers.AppendChild(new AsciiTextHeader("X-MS-Exchange-Organization-OriginalSize", mimeSize.ToString(NumberFormatInfo.InvariantInfo)));
            headers.RemoveAll("X-MS-Exchange-Organization-OriginalArrivalTime");
            Header newChild3 = new AsciiTextHeader("X-MS-Exchange-Organization-OriginalArrivalTime", Util.FormatOrganizationalMessageArrivalTime(this.OriginalCreateTime));

            headers.AppendChild(newChild3);
            headers.RemoveAll("X-MS-Exchange-Organization-MessageSource");
            Header newChild4 = new AsciiTextHeader("X-MS-Exchange-Organization-MessageSource", "StoreDriver");

            headers.AppendChild(newChild4);
            headers.AppendChild(new AsciiTextHeader("X-MS-Exchange-Transport-FromEntityHeader", RoutingEndpoint.Hosted.ToString()));
            headers.AppendChild(new AsciiTextHeader("X-MS-Exchange-Organization-FromEntityHeader", RoutingEndpoint.Hosted.ToString()));
            message.Directionality = MailDirectionality.Originating;
            message.UpdateDirectionalityAndScopeHeaders();
        }
        private bool TryGetHeaderValue(string headerName, out string value)
        {
            HeaderList headers    = this.message.MimeDocument.RootPart.Headers;
            TextHeader textHeader = headers.FindFirst(headerName) as TextHeader;

            value = null;
            if (textHeader == null)
            {
                InitiationMessage.diag.TraceDebug <string>((long)this.GetHashCode(), "'{0}' header not found from message.", headerName);
                return(false);
            }
            if (!textHeader.TryGetValue(out value) || string.IsNullOrEmpty(value))
            {
                InitiationMessage.diag.TraceDebug <string>((long)this.GetHashCode(), "'{0}' header cannot be read from message.", headerName);
                return(false);
            }
            return(true);
        }
Example #15
0
        internal static IEnumerable <CultureInfo> GetDsnCultures(MailboxSession mailboxSession, HeaderList headerList, DsnHumanReadableWriter dsnWriter)
        {
            if (mailboxSession != null)
            {
                return(mailboxSession.InternalGetMailboxCultures());
            }
            CultureInfo cultureInfo = null;

            if (headerList != null)
            {
                Header acceptLanguageHeader  = null;
                Header contentLanguageHeader = headerList.FindFirst(HeaderId.ContentLanguage);
                cultureInfo = dsnWriter.GetDsnCulture(acceptLanguageHeader, contentLanguageHeader, true, null);
            }
            if (cultureInfo != null)
            {
                return(new CultureInfo[]
                {
                    cultureInfo
                });
            }
            return(Array <CultureInfo> .Empty);
        }
Example #16
0
        public static void CopyHeaderBetweenList(HeaderList sourceHeaderList, HeaderList targetHeaderList, string headerName, bool onlyWriteFirstHeader)
        {
            Header header = sourceHeaderList.FindFirst(headerName);

            while (header != null)
            {
                if (onlyWriteFirstHeader)
                {
                    Header header2 = targetHeaderList.FindFirst(headerName);
                    if (header2 != null)
                    {
                        header2.Value = header.Value;
                        return;
                    }
                    targetHeaderList.AppendChild(header.Clone());
                    return;
                }
                else
                {
                    targetHeaderList.AppendChild(header.Clone());
                    header = sourceHeaderList.FindNext(header);
                }
            }
        }
Example #17
0
        void SCPRoutingAgent_OnResolvedMessage(ResolvedMessageEventSource source, QueuedMessageEventArgs e)
        {
            try
            {
                WriteLine("Start SCPRoutingAgent_OnResolvedMessage");

                WriteLine("\tFromAddress: " + e.MailItem.FromAddress.ToString());
                WriteLine("\tSubject: " + e.MailItem.Message.Subject.ToString());
                WriteLine("\tMapiMessageClass: " + e.MailItem.Message.MapiMessageClass.ToString());

                MimeDocument mdMimeDoc    = e.MailItem.Message.MimeDocument;
                HeaderList   hlHeaderlist = mdMimeDoc.RootPart.Headers;
                Header       mhProcHeader = hlHeaderlist.FindFirst("X-SCP");

                if (mhProcHeader == null)
                {
                    WriteLine("\tTouched: " + "No");

                    if (!e.MailItem.Message.IsSystemMessage)
                    {
                        bool touched = false;

                        if (e.MailItem.FromAddress.DomainPart != null)
                        {
                            foreach (EnvelopeRecipient recp in e.MailItem.Recipients)
                            {
                                WriteLine("\t\tFrom: " + e.MailItem.Message.From.SmtpAddress.ToString().ToLower());
                                WriteLine("\t\tTo: " + recp.Address.ToString().ToLower());
                                string[] tmpFrom = e.MailItem.Message.From.SmtpAddress.Split('@');
                                string[] tmpTo   = recp.Address.ToString().Split('@');
                                if (IsMessageBetweenTenants(tmpFrom[1].ToLower(), tmpTo[1].ToLower()))
                                {
                                    WriteLine("\t\tMessage routed to domain: " + tmpTo[1].ToLower() + routingDomain);
                                    RoutingDomain   myRoutingDomain   = new RoutingDomain(tmpTo[1].ToLower() + routingDomain);
                                    RoutingOverride myRoutingOverride = new RoutingOverride(myRoutingDomain, DeliveryQueueDomain.UseOverrideDomain);
                                    source.SetRoutingOverride(recp, myRoutingOverride);
                                    touched = true;
                                }
                            }
                        }
                        else
                        {
                            if ((e.MailItem.Message.MapiMessageClass.ToString() == "IPM.Note.Rules.OofTemplate.Microsoft") &
                                blockInternalInterTenantOOF)
                            {
                                WriteLine("\t\tOOF From: " + e.MailItem.Message.From.SmtpAddress);
                                if (e.MailItem.Message.From.SmtpAddress.Contains("@"))
                                {
                                    string[] tmpFrom = e.MailItem.Message.From.SmtpAddress.Split('@');
                                    foreach (EnvelopeRecipient recp in e.MailItem.Recipients)
                                    {
                                        WriteLine("\t\tTo: " + recp.Address.ToString().ToLower());
                                        string[] tmpTo = recp.Address.ToString().Split('@');
                                        if (IsMessageBetweenTenants(tmpFrom[1].ToLower(), tmpTo[1].ToLower()))
                                        {
                                            WriteLine("\t\tRemove: " + tmpTo[1].ToLower());
                                            e.MailItem.Recipients.Remove(recp);
                                        }
                                    }
                                }
                            }
                        }

                        if (touched)
                        {
                            MimeNode   lhLasterHeader = hlHeaderlist.LastChild;
                            TextHeader nhNewHeader    = new TextHeader("X-SCP", "Logged00");
                            hlHeaderlist.InsertBefore(nhNewHeader, lhLasterHeader);
                        }
                    }
                    else
                    {
                        WriteLine("\tSystem Message");
                    }
                }
                else
                {
                    WriteLine("\tTouched: " + "Yes");
                }
            }

            catch (Exception ex)
            {
                WriteLine("\t[Error] Error :" + ex.Message);
                LogErrorToEventLog("[Error] [OnResolvedMessage] Error :" + ex.Message);
            }

            WriteLine("End SCPRoutingAgent_OnResolvedMessage");
        }
Example #18
0
 internal static string GetHeaderValue(HeaderList headers, HeaderId headerId, InboundConversionOptions options)
 {
     return(MimeHelpers.GetHeaderValue(headers.FindFirst(headerId), options));
 }
Example #19
0
        public static void Convert(Stream source, Stream destination)
        {
            int i = 0;

            byte[][] array  = null;
            byte[]   array2 = null;
            using (Stream stream = new SuppressCloseStream(source))
            {
                using (MimeReader mimeReader = new MimeReader(stream, true, DecodingOptions.Default, MimeLimits.Unlimited, true, false))
                {
                    while (mimeReader.ReadNextPart())
                    {
                        while (i >= mimeReader.Depth)
                        {
                            byte[] array3 = array[--i];
                            if (array3 != null)
                            {
                                destination.Write(array3, 0, array3.Length - 2);
                                destination.Write(MimeString.TwoDashesCRLF, 0, MimeString.TwoDashesCRLF.Length);
                            }
                        }
                        if (i > 0)
                        {
                            byte[] array3 = array[i - 1];
                            if (array3 != null)
                            {
                                destination.Write(array3, 0, array3.Length);
                            }
                        }
                        HeaderList        headerList        = HeaderList.ReadFrom(mimeReader);
                        ContentTypeHeader contentTypeHeader = headerList.FindFirst(HeaderId.ContentType) as ContentTypeHeader;
                        bool flag;
                        bool flag2;
                        bool flag3;
                        EightToSevenBitConverter.Analyse(contentTypeHeader, out flag, out flag2, out flag3);
                        Header header = headerList.FindFirst(HeaderId.ContentTransferEncoding);
                        if (flag2 || flag)
                        {
                            if (header != null)
                            {
                                headerList.RemoveChild(header);
                            }
                            headerList.WriteTo(destination);
                            byte[] array3;
                            if (flag)
                            {
                                array3 = null;
                                destination.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                            }
                            else
                            {
                                array3 = MimePart.GetBoundary(contentTypeHeader);
                            }
                            if (array == null)
                            {
                                array = new byte[4][];
                            }
                            else if (array.Length == i)
                            {
                                byte[][] array4 = new byte[array.Length * 2][];
                                Array.Copy(array, 0, array4, 0, i);
                                array = array4;
                            }
                            array[i++] = array3;
                        }
                        else
                        {
                            Stream stream2 = null;
                            try
                            {
                                stream2 = mimeReader.GetRawContentReadStream();
                                if (header != null && stream2 != null)
                                {
                                    ContentTransferEncoding encodingType = MimePart.GetEncodingType(header.FirstRawToken);
                                    if (encodingType == ContentTransferEncoding.EightBit || encodingType == ContentTransferEncoding.Binary)
                                    {
                                        if (flag3)
                                        {
                                            header.RawValue = MimeString.QuotedPrintable;
                                            stream2         = new EncoderStream(stream2, new QPEncoder(), EncoderStreamAccess.Read);
                                        }
                                        else
                                        {
                                            header.RawValue = MimeString.Base64;
                                            stream2         = new EncoderStream(stream2, new Base64Encoder(), EncoderStreamAccess.Read);
                                        }
                                    }
                                }
                                headerList.WriteTo(destination);
                                destination.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                                if (stream2 != null)
                                {
                                    DataStorage.CopyStreamToStream(stream2, destination, long.MaxValue, ref array2);
                                }
                            }
                            finally
                            {
                                if (stream2 != null)
                                {
                                    stream2.Dispose();
                                }
                            }
                        }
                    }
                    while (i > 0)
                    {
                        byte[] array3 = array[--i];
                        if (array3 != null)
                        {
                            destination.Write(array3, 0, array3.Length - 2);
                            destination.Write(MimeString.TwoDashesCRLF, 0, MimeString.TwoDashesCRLF.Length);
                        }
                    }
                }
            }
        }