如何将图像文件放入MemoryStream并将其附加到电子邮件中

时间:2017-04-20 12:59:48

标签: c# email encryption email-attachments memorystream

我加密了一张图片, 现在我需要阅读该图像,解密并将其附加到电子邮件中。

首先,我尝试放置一个图像文件并将其附加到电子邮件中, 但是当我收到电子邮件时,附件中的图片已损坏!

我尝试了许多不同的方法,但没有成功。 (我创建了仅用于测试的Windows应用程序项目,最终我需要在MVC Web应用程序项目中使用解决方案)

private void btnSend_Click(object sender, EventArgs e)
{
    var filePath = "D:\\3.jpg"; // path to none encrypted image file

    var ms = new MemoryStream(File.ReadAllBytes(filePath));

    // Create attachment
    var attach = new Attachment(ms, new ContentType(MediaTypeNames.Image.Jpeg));
    attach.ContentDisposition.FileName = "sample.jpg";

    // Send Email
    IMailSender mailSender = new MailSender();
    var isSuccess = mailSender.Send(
      "sample email title",
      "sample@gmail.com",
      "sample subject",
      "sample body",
      new Attachment[] { attach });

    MessageBox.Show(isSuccess ? "Email sent successfully" : mailSender.ErrorMessage);

}

1 个答案:

答案 0 :(得分:0)

using (MailMessage Message = new MailMessage())
{
    Message.From = new MailAddress("from@mail.com");
    Message.Subject = "My Subject";
    Message.Body = "My Body";
    Message.To.Add(new MailAddress("to@mail.com"));

    //Attach more file
    foreach (var item in Attachment)
    {
        MemoryStream ms = new MemoryStream(File.ReadAllBytes(filePath));

        Attachment Data = new Attachment(ms, "FileName");
        ContentDisposition Disposition = Data.ContentDisposition;
        Disposition.CreationDate = DateTime.UtcNow.AddHours(-5);
        Disposition.ModificationDate = DateTime.UtcNow.AddHours(-5);
        Disposition.ReadDate = DateTime.UtcNow.AddHours(-5);
        Data.ContentType = new ContentType(MediaTypeNames.Application.Pdf);
        Message.Attachments.Add(Data);
    }

    SmtpClient smtp = new SmtpClient("SmtpAddress", "SmtpPort");
    smtp.Credentials = new NetworkCredential("SmtpUser", "SmtpPassword");
    await smtp.SendMailAsync(Message);
}

我希望这会有所帮助