diff --git a/MimeKit/MimeMessage.cs b/MimeKit/MimeMessage.cs index f4eaf74f4d..31ad90254a 100644 --- a/MimeKit/MimeMessage.cs +++ b/MimeKit/MimeMessage.cs @@ -2143,6 +2143,17 @@ IEnumerable
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) diff --git a/UnitTests/MimeMessageTests.cs b/UnitTests/MimeMessageTests.cs index 6fe9dc7353..c5ae4ed8c7 100644 --- a/UnitTests/MimeMessageTests.cs +++ b/UnitTests/MimeMessageTests.cs @@ -104,6 +104,40 @@ public void TestArgumentExceptions () Assert.Throws (() => MimeMessage.CreateFromMailMessage (null)); } + [Test] + public void TestPrependHeader () + { + string rawMessageText = @"Date: Fri, 22 Jan 2016 8:44:05 -0500 (EST) +From: MimeKit Unit Tests +To: MimeKit Unit Tests +Subject: This is a test off prepending headers. +Message-Id: +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 () {