public async Task <CreateUserResponseModel> CreateAsync(CreateUserModel createUserModel)
        {
            var user = _mapper.Map <ApplicationUser>(createUserModel);

            var result = await _userManager.CreateAsync(user, createUserModel.Password);

            if (!result.Succeeded)
            {
                throw new BadRequestException(result.Errors.FirstOrDefault().Description);
            }

            var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var emailTemplate = await _templateService.GetTemplateAsync(TemplateConstants.ConfirmationEmail);

            var emailBody = _templateService.ReplaceInTemplate(emailTemplate,
                                                               new Dictionary <string, string> {
                { "{UserId}", user.Id }, { "{Token}", token }
            });

            await _emailService.SendEmailAsync(EmailMessage.Create(user.Email, emailBody, "[N-Tier]Confirm your email"));

            return(new CreateUserResponseModel
            {
                Id = Guid.Parse((await _userManager.FindByNameAsync(user.UserName)).Id)
            });
        }
        internal static EmailMessage GenerateDecisionNotTakenNotification(RoutingAddress from, RoutingAddress recipient, string subject, string threadIndex, string threadTopic, string decisionMaker, bool?decision, ExDateTime?decisionTime, Header acceptLanguageHeader, Header contentLanguageHeader, CultureInfo fallbackCulture)
        {
            if (from.Equals(RoutingAddress.NullReversePath) || recipient.Equals(RoutingAddress.NullReversePath) || !from.IsValid || !recipient.IsValid)
            {
                return(null);
            }
            DsnHumanReadableWriter dsnHumanReadableWriter      = Components.DsnGenerator.DsnHumanReadableWriter;
            ApprovalInformation    decisionConflictInformation = dsnHumanReadableWriter.GetDecisionConflictInformation(subject, decisionMaker, decision, decisionTime, acceptLanguageHeader, contentLanguageHeader, fallbackCulture);
            EmailMessage           emailMessage = EmailMessage.Create(BodyFormat.Html, false, decisionConflictInformation.MessageCharset.Name);

            emailMessage.From = new EmailRecipient(string.Empty, from.ToString());
            emailMessage.To.Add(new EmailRecipient(string.Empty, recipient.ToString()));
            emailMessage.Subject = decisionConflictInformation.Subject;
            using (Stream contentWriteStream = emailMessage.Body.GetContentWriteStream())
            {
                dsnHumanReadableWriter.WriteHtmlModerationBody(contentWriteStream, decisionConflictInformation);
                contentWriteStream.Flush();
            }
            Header header = Header.Create("X-MS-Exchange-Organization-SCL");

            header.Value = "-1";
            emailMessage.RootPart.Headers.AppendChild(header);
            Header header2 = (TextHeader)Header.Create("Thread-Index");

            header2.Value = threadIndex;
            emailMessage.RootPart.Headers.AppendChild(header2);
            Header header3 = (TextHeader)Header.Create("Thread-Topic");

            header3.Value = threadTopic;
            emailMessage.RootPart.Headers.AppendChild(header3);
            return(emailMessage);
        }
Esempio n. 3
0
        private EmailMessage CreateFblRequestMessage(FblRequestParameters requestParameters)
        {
            if (requestParameters == null)
            {
                throw new ArgumentNullException("requestParameters", "Cannot create FBL Request Message from null request parameters.");
            }
            EmailMessage emailMessage = EmailMessage.Create();

            this.AddHeader(emailMessage, "X-Version", "1");
            this.AddHeader(emailMessage, "X-GuidCustomer", requestParameters.CustomerGuid.ToString());
            if (requestParameters.IsClassifyRequest())
            {
                this.AddHeader(emailMessage, "X-GuidMail", requestParameters.MailGuid.ToString());
                this.AddHeader(emailMessage, "X-Class", requestParameters.MessageClass);
            }
            else
            {
                RoutingAddress routingAddress = new RoutingAddress(requestParameters.PrimaryEmail);
                this.AddHeader(emailMessage, "X-UserName", routingAddress.LocalPart);
                this.AddHeader(emailMessage, "X-Domain", routingAddress.DomainPart);
                this.AddHeader(emailMessage, "X-OptIn", requestParameters.OptIn ? "1" : "0");
            }
            this.AddEncryptedMessageRoutingHeaderToMessage(emailMessage);
            return(emailMessage);
        }
Esempio n. 4
0
        public void Given_Create_When_ParametersArePassed_Then_ShouldCreateEmailMessage()
        {
            // act
            var emailMessage = EmailMessage.Create("test", "Test subject", "hello");

            // assert
            Assert.NotNull(emailMessage);
        }
Esempio n. 5
0
        private bool TryGenerateMessageFromMsgFileData(string defaultDomain)
        {
            bool result;

            using (Stream stream = new MemoryStream(this.MessageFileData))
            {
                using (MessageItem messageItem = MessageItem.CreateInMemory(StoreObjectSchema.ContentConversionProperties))
                {
                    using (Stream stream2 = new MemoryStream())
                    {
                        try
                        {
                            InboundConversionOptions inboundConversionOptions = new InboundConversionOptions(defaultDomain);
                            inboundConversionOptions.UserADSession = this.GetRecipientSession();
                            OutboundConversionOptions outboundConversionOptions = new OutboundConversionOptions(defaultDomain);
                            outboundConversionOptions.UserADSession = inboundConversionOptions.UserADSession;
                            ItemConversion.ConvertMsgStorageToItem(stream, messageItem, inboundConversionOptions);
                            if (this.WasSpecifiedByUser("Sender"))
                            {
                                SmtpAddress sender  = this.Sender;
                                Participant sender2 = new Participant(string.Empty, (string)this.Sender, "SMTP");
                                messageItem.Sender = sender2;
                            }
                            ItemConversion.ConvertItemToSummaryTnef(messageItem, stream2, outboundConversionOptions);
                            stream2.Position = 0L;
                            this.message     = EmailMessage.Create(stream2);
                            result           = true;
                        }
                        catch (CorruptDataException ex)
                        {
                            base.WriteVerbose(Strings.UnableToCreateFromMsg(ex.Message));
                            result = false;
                        }
                        catch (ConversionFailedException ex2)
                        {
                            base.WriteVerbose(Strings.UnableToCreateFromMsg(ex2.Message));
                            result = false;
                        }
                        catch (PropertyErrorException ex3)
                        {
                            base.WriteVerbose(Strings.UnableToCreateFromMsg(ex3.Message));
                            result = false;
                        }
                        catch (StoragePermanentException ex4)
                        {
                            base.WriteVerbose(Strings.UnableToCreateFromMsg(ex4.Message));
                            result = false;
                        }
                        catch (StorageTransientException ex5)
                        {
                            base.WriteVerbose(Strings.UnableToCreateFromMsg(ex5.Message));
                            result = false;
                        }
                    }
                }
            }
            return(result);
        }
        private async Task SendEmail(Event ev)
        {
            var body   = string.Format(EmailTemplates.ContentAdded, ev.Name);
            var emails =
                ev.Subscriptions.Select(x => EmailMessage.Create(x.Email, body, EmailTemplates.ContentAddedSubject));

            foreach (var emailMessage in emails)
            {
                await emailService.Send(emailMessage);
            }
        }
Esempio n. 7
0
 private void GenerateDefaultMessage()
 {
     using (MemoryStream memoryStream = new MemoryStream())
     {
         StreamWriter streamWriter = new StreamWriter(memoryStream, Encoding.ASCII);
         this.AddToFromHeader(streamWriter);
         this.AddDefaultBody(streamWriter);
         streamWriter.Flush();
         memoryStream.Flush();
         memoryStream.Position = 0L;
         this.message          = EmailMessage.Create(memoryStream);
     }
 }
Esempio n. 8
0
        public void Given_Create_When_ParametersAreGiven_Then_ShouldSetParameters()
        {
            // arrange
            var to      = "test";
            var subject = "Test subject";
            var body    = "hello";

            // act
            var emailMessage = EmailMessage.Create(to, subject, body);

            // assert
            Assert.Equal(to, emailMessage.To);
            Assert.Equal(subject, emailMessage.Subject);
            Assert.Equal(body, emailMessage.Body);
        }
Esempio n. 9
0
            public async Task <Unit> Handle(CreateEmailMessage command, CancellationToken cancellationToken)
            {
                var messageBody = GetMessageBody(command.Body, command.IsHtmlBody);
                var sender      = EmailAddress.Create(command.Sender);
                var recipients  = command.Recipients?
                                  .Select(EmailAddress.Create)
                                  .Where(x => !(x is null));

                var message = command.IsPendingEmail
                    ? EmailMessage.CreatePending(command.Subject, messageBody, sender, recipients)
                    : EmailMessage.Create(command.Subject, messageBody, sender, recipients);

                await this.repository.InsertMessageAsync(message);

                return(Unit.Value);
            }
Esempio n. 10
0
        private bool TryGenerateMessageFromEmlFileData(out string error)
        {
            error = string.Empty;
            MimeDocument mimeDocument = new MimeDocument();

            using (Stream stream = new MemoryStream(this.MessageFileData))
            {
                try
                {
                    mimeDocument.ComplianceMode = MimeComplianceMode.Strict;
                    mimeDocument.Load(stream, CachingMode.Copy);
                    this.message = EmailMessage.Create(mimeDocument);
                }
                catch (ArgumentNullException)
                {
                    return(false);
                }
                catch (ArgumentException)
                {
                    return(false);
                }
                catch (InvalidOperationException)
                {
                    return(false);
                }
                catch (NotSupportedException)
                {
                    return(false);
                }
                catch (MimeException ex)
                {
                    error = ex.Message;
                    return(false);
                }
            }
            if (mimeDocument.ComplianceStatus != MimeComplianceStatus.Compliant)
            {
                error = Strings.MimeDoesNotComplyWithStandards;
                return(false);
            }
            return(true);
        }
        public void DisclaimerHandlerTextTest()
        {
            const string value = "DisclaimerHandlerTextTest Value";

            var emailMessage = EmailMessage.Create(BodyFormat.Text);

            emailMessage.From = new EmailRecipient("Alice", "*****@*****.**");
            emailMessage.To.Add(new EmailRecipient("Bob", "*****@*****.**"));
            emailMessage.SetBody("DisclaimerHandlerHtmlTest Body");
            emailMessage.Subject = "DisclaimerHandlerHtmlTest Subject";

            TestObject.Text = value;

            PrepareLogger();

            TestObject.Execute(new EmailItem(emailMessage));

            string body = emailMessage.GetBody();

            Assert.IsTrue(body.Contains(value));
        }
        public void DisclaimerHandlerHtmlTest()
        {
            const string value        = "<pre>DisclaimerHandlerHtmlTest Value</pre>";
            const string wrappedValue = "<html><head><title></title></head><body>" + value + "</body></html>";

            var emailMessage = EmailMessage.Create(BodyFormat.Html);

            emailMessage.From = new EmailRecipient("Alice", "*****@*****.**");
            emailMessage.To.Add(new EmailRecipient("Bob", "*****@*****.**"));
            emailMessage.SetBody("<html><head><title>DisclaimerHandlerHtmlTest Subject</title><body>DisclaimerHandlerHtmlTest Body</body></html>");
            emailMessage.Subject = "DisclaimerHandlerHtmlTest Subject";

            TestObject.Html = wrappedValue;

            PrepareLogger();

            TestObject.Execute(new EmailItem(emailMessage));

            string body = emailMessage.GetBody();

            Assert.IsTrue(body.Contains(value));
        }
 private void CacheDataFromOriginalMessage()
 {
     try
     {
         if (this.isOriginalMessageDataCached)
         {
             ModerationApprovalRequestWriter.diag.TraceDebug((long)this.GetHashCode(), "Original data cached.");
         }
         else
         {
             this.isOriginalMessageDataCached = true;
             ModerationApprovalRequestWriter.diag.TraceDebug((long)this.GetHashCode(), "Getting original message for cache.");
             this.CacheModeratedRecipients();
             this.originalMessageStream = this.GetOriginalMessageReadStream();
             if (this.originalMessageStream == null)
             {
                 ModerationApprovalRequestWriter.diag.TraceError(0L, "There is no original message attached in initiation message.");
             }
             else
             {
                 this.originalMimeDom = new MimeDocument();
                 this.originalMimeDom.Load(this.originalMessageStream, CachingMode.Source);
                 this.originalEmailMessage    = EmailMessage.Create(this.originalMimeDom);
                 this.originalToFormattedLine = ModerationApprovalRequestWriter.FormatRecipients(this.originalEmailMessage.To);
                 this.originalCcFormattedLine = ModerationApprovalRequestWriter.FormatRecipients(this.originalEmailMessage.Cc);
                 EmailRecipient sender = this.originalEmailMessage.Sender;
                 if (sender != null && !string.IsNullOrEmpty(sender.DisplayName))
                 {
                     if (!string.IsNullOrEmpty(sender.SmtpAddress) && this.organizationId != null && !IsInternalResolver.IsInternal(new RoutingAddress(sender.SmtpAddress), this.organizationId))
                     {
                         this.originalSenderDisplayName = sender.DisplayName + "(" + sender.SmtpAddress + ")";
                     }
                     else
                     {
                         this.originalSenderDisplayName = sender.DisplayName;
                     }
                 }
                 else
                 {
                     this.originalSenderDisplayName = (string)this.initiationMessage.Requestor;
                 }
                 this.originalMesssageBodyFormat = this.originalEmailMessage.Body.BodyFormat;
                 string  charsetName = this.originalEmailMessage.Body.CharsetName;
                 Charset charset;
                 if (!string.IsNullOrEmpty(charsetName) && Charset.TryGetCharset(charsetName, out charset) && charset.IsAvailable)
                 {
                     ModerationApprovalRequestWriter.diag.TraceDebug <string>((long)this.GetHashCode(), "original message body has charset {0}", charsetName);
                     this.originalMessageBodyCharset = charset;
                 }
                 else
                 {
                     ModerationApprovalRequestWriter.diag.TraceDebug <string>((long)this.GetHashCode(), "original message charset not valid {0}", charsetName);
                 }
                 this.hasInlineAttachment = false;
                 if (this.originalMesssageBodyFormat == Microsoft.Exchange.Data.Transport.Email.BodyFormat.Rtf)
                 {
                     if (this.originalEmailMessage.Attachments != null && this.originalEmailMessage.Attachments.Count > 0)
                     {
                         this.hasInlineAttachment = true;
                     }
                 }
                 else if (this.originalMesssageBodyFormat != Microsoft.Exchange.Data.Transport.Email.BodyFormat.Text && this.originalMesssageBodyFormat == Microsoft.Exchange.Data.Transport.Email.BodyFormat.Html && this.originalEmailMessage.Attachments != null && this.originalEmailMessage.Attachments.Count > 0)
                 {
                     foreach (Attachment attachment in this.originalEmailMessage.Attachments)
                     {
                         if (attachment.AttachHidden || attachment.AttachmentType == AttachmentType.Inline)
                         {
                             this.hasInlineAttachment = true;
                             break;
                         }
                     }
                 }
                 this.isOpaqueMessage = this.originalEmailMessage.IsOpaqueMessage;
             }
         }
     }
     catch (ExchangeDataException arg)
     {
         ModerationApprovalRequestWriter.diag.TraceError <ExchangeDataException>((long)this.GetHashCode(), "Cannot cache all data required for moderation approval request {0}", arg);
     }
 }
 public static EmailMessage CreateHtmlEmailMessage(string subject, string body)
 {
     return(FillEmailMessage(EmailMessage.Create(BodyFormat.Html), subject, body));
 }
Esempio n. 15
0
 public static EmailMessage GenerateContentReport(SmtpAddress arbitrationAddress, SmtpAddress reportToAddress, StoreSession session, bool isArbitration)
 {
     if (arbitrationAddress.IsValidAddress && reportToAddress.IsValidAddress)
     {
         EmailMessage   emailMessage = EmailMessage.Create();
         RoutingAddress address      = GlobalConfigurationBase <MicrosoftExchangeRecipient, MicrosoftExchangeRecipientConfiguration> .Instance.Address;
         emailMessage.From = new EmailRecipient(null, (string)address);
         emailMessage.To.Add(new EmailRecipient(null, (string)reportToAddress));
         emailMessage.Subject = "Arbitration Mailbox Content Report: " + arbitrationAddress.ToString();
         using (Stream contentWriteStream = emailMessage.Body.GetContentWriteStream())
         {
             using (StreamWriter streamWriter = new StreamWriter(contentWriteStream))
             {
                 if (!isArbitration)
                 {
                     streamWriter.WriteLine("This mailbox is not an approval arbitration mailbox. This report is only generated for approval arbitration mailboxes.");
                     return(emailMessage);
                 }
                 Attachment attachment = emailMessage.Attachments.Add("formattedDetails.txt");
                 using (Stream contentWriteStream2 = attachment.GetContentWriteStream())
                 {
                     using (Folder folder = Folder.Bind((MailboxSession)session, DefaultFolderType.Inbox))
                     {
                         using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, null, null, new PropertyDefinition[]
                         {
                             ItemSchema.Id
                         }))
                         {
                             object[][] rows = queryResult.GetRows(10000);
                             int        num  = 0;
                             int        num2 = 0;
                             TimeSpan   t    = default(TimeSpan);
                             TimeSpan   t2   = default(TimeSpan);
                             while (rows != null && rows.Length > 0)
                             {
                                 foreach (object[] array2 in rows)
                                 {
                                     StoreObjectId objectId = ((VersionedId)array2[0]).ObjectId;
                                     using (MessageItem messageItem = MessageItem.Bind(session, objectId, ArbitrationMailboxReport.ApprovalProperties))
                                     {
                                         string         valueOrDefault   = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalRequestor);
                                         string         valueOrDefault2  = messageItem.GetValueOrDefault <string>(ItemSchema.DisplayCc);
                                         string         valueOrDefault3  = messageItem.GetValueOrDefault <string>(ItemSchema.Subject);
                                         string         valueOrDefault4  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalAllowedDecisionMakers);
                                         string         valueOrDefault5  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalDecisionMakersNdred);
                                         string         valueOrDefault6  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalRequestMessageId);
                                         string         valueOrDefault7  = messageItem.GetValueOrDefault <string>(ItemSchema.InternetMessageId);
                                         string         valueOrDefault8  = messageItem.GetValueOrDefault <string>(ItemSchema.InternetReferences);
                                         string         valueOrDefault9  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalDecisionMaker);
                                         ApprovalStatus?valueAsNullable  = messageItem.GetValueAsNullable <ApprovalStatus>(MessageItemSchema.ApprovalStatus);
                                         ExDateTime?    valueAsNullable2 = messageItem.GetValueAsNullable <ExDateTime>(MessageItemSchema.ApprovalDecisionTime);
                                         ExDateTime?    valueAsNullable3 = messageItem.GetValueAsNullable <ExDateTime>(ItemSchema.ReceivedTime);
                                         ExDateTime?    valueAsNullable4 = messageItem.GetValueAsNullable <ExDateTime>(ItemSchema.RetentionDate);
                                         if (valueAsNullable3 != null)
                                         {
                                             if (valueAsNullable2 == null)
                                             {
                                                 ExDateTime utcNow = ExDateTime.UtcNow;
                                                 t2 += utcNow - valueAsNullable3.Value;
                                                 num2++;
                                             }
                                             else if (valueAsNullable3 <= valueAsNullable2)
                                             {
                                                 t += valueAsNullable2.Value - valueAsNullable3.Value;
                                                 num++;
                                             }
                                         }
                                         streamWriter.WriteLine("Initiation Message ID:" + valueOrDefault7);
                                         streamWriter.WriteLine("Original Message ID:" + valueOrDefault8);
                                         streamWriter.WriteLine("Sender:" + valueOrDefault);
                                         streamWriter.WriteLine("Moderated Recipient Addresses:" + valueOrDefault2);
                                         streamWriter.WriteLine("Message Subject:" + valueOrDefault3);
                                         streamWriter.WriteLine("Moderators:" + valueOrDefault4);
                                         streamWriter.WriteLine("Moderators (total; not delivered; away):" + valueOrDefault5);
                                         streamWriter.WriteLine("Approval Request Message ID:" + valueOrDefault6);
                                         streamWriter.WriteLine("Decision maker:" + valueOrDefault9);
                                         streamWriter.WriteLine("Decision status:" + valueAsNullable);
                                         streamWriter.WriteLine("Decision Time:" + valueAsNullable2);
                                         streamWriter.WriteLine("Received Time:" + valueAsNullable3);
                                         streamWriter.WriteLine("Expiry Time:" + valueAsNullable4);
                                         streamWriter.WriteLine();
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault7);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault8);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault2);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault3);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault4);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault5);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault6);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault9);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueAsNullable);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault6);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueAsNullable2);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueAsNullable3);
                                         Utf8Csv.EncodeEscapeAndWriteLine(contentWriteStream2, (valueAsNullable4 != null) ? valueAsNullable4.ToString() : string.Empty);
                                     }
                                 }
                                 rows = queryResult.GetRows(10000);
                             }
                             streamWriter.WriteLine("Summary:");
                             streamWriter.WriteLine("Messages with a decision:" + num);
                             if (num > 0)
                             {
                                 streamWriter.WriteLine("Average decision time:" + TimeSpan.FromSeconds(t.TotalSeconds / (double)num));
                             }
                             streamWriter.WriteLine("Messages without a decision:" + num2);
                             if (num2 > 0)
                             {
                                 streamWriter.WriteLine("Average waiting time:" + TimeSpan.FromSeconds(t2.TotalSeconds / (double)num2));
                             }
                         }
                     }
                 }
                 return(emailMessage);
             }
         }
     }
     return(null);
 }
        // Token: 0x06000174 RID: 372 RVA: 0x0000A754 File Offset: 0x00008954
        private static int WriteMimePartsToEmailMessage(IEnumerable mimeParts, string toAddress, string fromAddress, Guid externalOrganizationId)
        {
            int num = 0;

            if (string.IsNullOrEmpty(fromAddress))
            {
                fromAddress = "EHAJournalConfirmation@" + NativeHelpers.GetLocalComputerFqdn(false);
            }
            using (EmailMessage emailMessage = EmailMessage.Create(BodyFormat.Text))
            {
                emailMessage.Subject = DateTime.UtcNow.ToString();
                emailMessage.To.Add(new EmailRecipient(toAddress, toAddress));
                emailMessage.Sender = new EmailRecipient(fromAddress, fromAddress);
                Header header = Header.Create("X-Sender");
                header.Value = fromAddress;
                emailMessage.MimeDocument.RootPart.Headers.AppendChild(header);
                header       = Header.Create("X-Receiver");
                header.Value = toAddress;
                emailMessage.MimeDocument.RootPart.Headers.AppendChild(header);
                header       = Header.Create("X-CreatedBy");
                header.Value = "MSExchange12";
                emailMessage.MimeDocument.RootPart.Headers.AppendChild(header);
                header       = Header.Create("X-EndOfInjectedXHeaders");
                header.Value = " ";
                emailMessage.MimeDocument.RootPart.Headers.AppendChild(header);
                Header header2 = Header.Create("X-MS-Exchange-Organization-ArchiveReplication-DataType");
                header2.Value = " ";
                emailMessage.MimeDocument.RootPart.Headers.AppendChild(header2);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (MetaExtractMime metaExtractMime = new MetaExtractMime(fromAddress, memoryStream))
                    {
                        metaExtractMime.SetContentDescriptionsProvider(EHALogSearchComponent.contentDescriptions);
                        foreach (object obj in mimeParts)
                        {
                            EHALogSearchComponent.ConfirmationWrapper confirmationWrapper = (EHALogSearchComponent.ConfirmationWrapper)obj;
                            try
                            {
                                if (metaExtractMime.AddBlobPart(confirmationWrapper.Confirmation, false, confirmationWrapper.EhaMessageId, confirmationWrapper.EoaMessageStatus))
                                {
                                    num++;
                                }
                            }
                            catch (XmlException ex)
                            {
                                EHALogSearchComponent.logger.LogEvent(MSExchangeTransportLogSearchEventLogConstants.Tuple_TransportSyncLogEntryProcessingFailure, DateTime.UtcNow.Hour.ToString(), new object[]
                                {
                                    ex
                                });
                                ExTraceGlobals.ServiceTracer.TraceError <string, XmlException>(0L, "Failed to add confirmation part to message body. MessageId={0}; XmlException={1}", confirmationWrapper.EhaMessageId, ex);
                            }
                        }
                        metaExtractMime.InsertLastPartEndingBoundary();
                        using (Stream contentWriteStream = emailMessage.Body.GetContentWriteStream())
                        {
                            using (StreamWriter streamWriter = new StreamWriter(contentWriteStream))
                            {
                                memoryStream.Seek(0L, SeekOrigin.Begin);
                                streamWriter.Write(new StreamReader(memoryStream).ReadToEnd());
                            }
                        }
                    }
                }
                if (!EHALogSearchComponent.SubmitMessage(emailMessage, toAddress, fromAddress, externalOrganizationId))
                {
                    num = 0;
                }
            }
            return(num);
        }
Esempio n. 17
0
 public EmailMessage GenerateTraceReport(SmtpAddress reportToAddress)
 {
     if (base.ProcessingTestMessage && reportToAddress.IsValidAddress)
     {
         EmailMessage   traceReport = EmailMessage.Create();
         RoutingAddress address     = GlobalConfigurationBase <MicrosoftExchangeRecipient, MicrosoftExchangeRecipientConfiguration> .Instance.Address;
         traceReport.From = new EmailRecipient(null, (string)address);
         traceReport.To.Add(new EmailRecipient(null, (string)reportToAddress));
         traceReport.Subject = "Tracing Report: " + base.Message.Subject;
         using (Stream contentWriteStream = traceReport.Body.GetContentWriteStream())
         {
             this.traceFormatter.CopyDataTo(contentWriteStream);
             contentWriteStream.Flush();
         }
         List <Exception> list = new List <Exception>();
         Exception        item;
         if (!RuleUtil.TryRunStoreCode(delegate
         {
             this.AddRuleDumpAttachment(traceReport, this.initialFolder, "mailbox-rules.xml");
         }, out item))
         {
             list.Add(item);
         }
         if (!RuleUtil.TryRunStoreCode(delegate
         {
             MailboxSession mailboxSession = this.StoreSession as MailboxSession;
             StoreObjectId defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox);
             if (defaultFolderId != this.initialFolder.Id.ObjectId)
             {
                 using (Folder folder = Folder.Bind(mailboxSession, defaultFolderId))
                 {
                     this.AddRuleDumpAttachment(traceReport, folder, "inbox-rules.xml");
                 }
             }
         }, out item))
         {
             list.Add(item);
         }
         if (!RuleUtil.TryRunStoreCode(delegate
         {
             this.AddOofHistoryAttachment(traceReport, "automatic-reply-history.xml");
         }, out item))
         {
             list.Add(item);
         }
         if (list.Count > 0)
         {
             Attachment attachment = traceReport.Attachments.Add("inboxrule-report-exceptions.txt");
             using (Stream contentWriteStream2 = attachment.GetContentWriteStream())
             {
                 using (TextWriter textWriter = new StreamWriter(contentWriteStream2))
                 {
                     foreach (Exception ex in list)
                     {
                         textWriter.WriteLine(ex.ToString());
                         textWriter.WriteLine();
                     }
                 }
             }
         }
         return(traceReport);
     }
     return(null);
 }