Skip to content

Commit

Permalink
Fixed message reserialization after prepending headers
Browse files Browse the repository at this point in the history
Fixes issue #524
  • Loading branch information
jstedfast committed Nov 23, 2019
1 parent efd5fca commit d055147
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
11 changes: 11 additions & 0 deletions MimeKit/MimeMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2143,6 +2143,17 @@ IEnumerable<Header> MergeHeaders ()
{
int mesgIndex = 0, bodyIndex = 0;

// write all of the prepended message headers first
while (mesgIndex < Headers.Count) {
var mesgHeader = Headers[mesgIndex];
if (mesgHeader.Offset.HasValue)
break;

yield return mesgHeader;
mesgIndex++;
}

// now merge the message and body headers as they appeared in the raw message
while (mesgIndex < Headers.Count && bodyIndex < Body.Headers.Count) {
var bodyHeader = Body.Headers[bodyIndex];
if (!bodyHeader.Offset.HasValue)
Expand Down
34 changes: 34 additions & 0 deletions UnitTests/MimeMessageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,40 @@ public void TestArgumentExceptions ()
Assert.Throws<ArgumentNullException> (() => MimeMessage.CreateFromMailMessage (null));
}

[Test]
public void TestPrependHeader ()
{
string rawMessageText = @"Date: Fri, 22 Jan 2016 8:44:05 -0500 (EST)
From: MimeKit Unit Tests <[email protected]>
To: MimeKit Unit Tests <[email protected]>
Subject: This is a test off prepending headers.
Message-Id: <[email protected]>
MIME-Version: 1.0
Content-Type: text/plain
This is the message body.
".Replace ("\r\n", "\n");
string expected = "X-Prepended: This is the prepended header\n" + rawMessageText;

using (var source = new MemoryStream (Encoding.UTF8.GetBytes (rawMessageText))) {
var parser = new MimeParser (source, MimeFormat.Default);
var message = parser.ParseMessage ();

message.Headers.Insert (0, new Header ("X-Prepended", "This is the prepended header"));

using (var serialized = new MemoryStream ()) {
var options = FormatOptions.Default.Clone ();
options.NewLineFormat = NewLineFormat.Unix;

message.WriteTo (options, serialized);

var result = Encoding.UTF8.GetString (serialized.ToArray ());

Assert.AreEqual (expected, result, "Reserialized message is not identical to the original.");
}
}
}

[Test]
public async Task TestReserialization ()
{
Expand Down

0 comments on commit d055147

Please sign in to comment.