roryok
roryok

Reputation: 9645

Returning a MimeKit message as a file to the browser

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", "[email protected]"));
    message.To.Add(new MailboxAddress("Alice", "[email protected]"));
    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?

Upvotes: 3

Views: 1624

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

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");

Upvotes: 8

Related Questions