3

I'm trying to return an eml file via the browser to a user. Thing is, there is no static eml file - the page builds it. I can build a sample message in MimeKit using the following method

public FileResult TestServe()
{
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("Joey", "joey@friends.com"));
    message.To.Add(new MailboxAddress("Alice", "alice@wonderland.com"));
    message.Subject = "How you doin?";

    message.Body = new TextPart("plain")
    {
        Text = @"Hey Alice,

        What are you up to this weekend? Monica is throwing one of her parties on
        Saturday and I was hoping you could make it.

        Will you be my +1?

        -- Joey
        "
    };

    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, message);

    return File(stream, "message/rfc822");
}

But when I run it I get this error

Type 'MimeKit.MimeMessage' in Assembly 'MimeKit, Version=0.27.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Is there a way around this? I can write the eml to a temp folder but obviously that comes with a performance hit so I'd rather not. Any ideas?

roryok
  • 9,325
  • 17
  • 71
  • 138
  • Have you tried using the [WriteTo](http://jstedfast.github.io/MimeKit/docs/MimeKit/MimeMessage.html#M:MimeKit.MimeMessage.WriteTo(System.IO.Stream,System.Threading.CancellationToken)) method and pass a new memory stream? – Jan Dec 16 '14 at 16:53

1 Answers1

8

As suggested in the comments you can use a WriteTo method:

var stream = new MemoryStream();
message.WriteTo(stream);
stream.Position = 0;

return File(stream, "message/rfc822");
jstedfast
  • 35,744
  • 5
  • 97
  • 110
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50