发送带附件的电子邮件时清空文件

时间:2015-09-29 14:15:51

标签: c# asp.net-mvc email email-attachments

我正在尝试使用邮件框架为MVC发送带附件的emil。

我可以毫无问题地发送邮件的电子邮件,但是,当我尝试发送带附件的电子邮件时,文件会变空。

这是我的代码:

dynamic emailNovoOrcamento = new Email("OrcamentosServicos/NotificaNovoOrcamento");
emailNovoOrcamento.To = usuario.UsuEmail;
emailNovoOrcamento.From = "no-reply@servicili.com";
emailNovoOrcamento.Subject = "Test...";

ContentType conteudo = new ContentType();
conteudo.MediaType = MediaTypeNames.Image.Jpeg;
conteudo.Name = "userPhoto.jpg";

Attachment imagemDestinatario = new Attachment(new getUserPhotoStream(usuario), conteudo);
emailNovoOrcamento.Attachments.Add(imagemDestinatario);
emailNovoOrcamento.Send();

getUserPhotoStream是一种将byte[]转换为Stream的方法:

public MemoryStream getUserPhotoStream(byte[] photo)
{
    MemoryStream imagemStream = new MemoryStream();
    Image imagem;
    MemoryStream imagemUsuarioStream = new MemoryStream(photo);

        imagem = Image.FromStream(imagemUsuarioStream);
        imagem.Save(imagemStream, ImageFormat.Jpeg);
        return imagemStream;
    }
}

当我通过电子邮件发送时,文件大小为0kb。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

在使用之前将流的位置设置为0:

// ...
imagem.Save(imagemStream, ImageFormat.Jpeg);
imagemStream.Position = 0;
return imagemStream;

答案 1 :(得分:0)

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

看到这一点,它可能会提供一些见解。我做了类似你的事,但从这里开始。