public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken) { _logger?.Log(LogLevel.Information, "Injecting headers into message"); try { //Add headers to the top of the message var bodyTextParts = message.BodyParts.OfType <TextPart>().ToList(); var htmlBody = bodyTextParts.LastOrDefault(btp => btp.IsHtml); var textBody = bodyTextParts.LastOrDefault(btp => !btp.IsHtml); if (htmlBody != null) { var bodyTagLocation = htmlBody.Text.IndexOf("<body>", StringComparison.OrdinalIgnoreCase); var insertLocation = bodyTagLocation == -1 ? 0 : bodyTagLocation + 6; htmlBody.Text = htmlBody.Text.Insert(insertLocation, $"\n{HeaderFormatter.GetHtmlHeaders(message)}"); } if (textBody != null) { textBody.Text = $"{HeaderFormatter.GetPlainTextHeaders(message)}\n{textBody.Text}"; } } catch (Exception exception) { _logger?.Log(LogLevel.Error, exception, "Error injecting headers into message"); //Don't throw, continue routing message } return(await Task.FromResult(message).ConfigureAwait(false)); }
public async Task <MimeMessage> RunAsync(MimeMessage message, ISessionContext context, IMessageTransaction transaction, CancellationToken cancellationToken) { _logger?.Log(LogLevel.Information, "Adding headers as an attachment"); try { var stream = new MemoryStream(); var streamWriter = new StreamWriter(stream); streamWriter.Write(HeaderFormatter.GetPlainTextHeaders(message)); streamWriter.Flush(); stream.Position = 0; var attachment = new MimePart("text", "plain") { Content = new MimeContent(stream), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = "OriginalHeaders.txt" }; //Add the attachment to the existing parent-level multipart if it exists. //Otherwise create a parent multipart and put the message body and attachment in it. if (message.Body is Multipart multipart) { multipart.Add(attachment); } else { message.Body = new Multipart("mixed") { message.Body, attachment }; } } catch (Exception exception) { _logger?.Log(LogLevel.Error, exception, "Error adding headers as an attachment"); //Don't throw, continue routing message } return(await Task.FromResult(message).ConfigureAwait(false)); }