一千萬個為什麽

搜索

ASP.NET使用電子郵件發送圖像附件而不保存到文件系統

我正在嘗試創建一個表單,該表單將發送帶有附加圖像的電子郵件,並且遇到了一些問題。我創建的表單相當大,所以我為此問題創建了一個小測試表單。電子郵件將發送,附件將存在於電子郵件中,但圖像已損壞或因為無法查看。

也..

我不想將圖像保存到文件系統。您可能認為將文件上傳中的圖像文件轉換為流是錯綜復雜的,但這是因為我正在處理的真實表單將允許通過單個文件上載添加多個文件並將保存在會話中因此,圖像不會直接在提交時來自fileupload控件。

文件:TestAttachSend.aspx

    

    

    
    
<title></title> </head> <body> <form id="form1" runat="server"> <div> 

Send Email with Image Attachment

            Email Address TO:  
Attach JPEG Image:



</div> </form> </body> </html>

文件:TestAttachSend.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.IO;

public partial class TestAttachSend : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (fuImage.HasFile && fuImage.PostedFile.ContentType == System.Net.Mime.MediaTypeNames.Image.Jpeg)
        {
            SmtpClient emailClient = new SmtpClient();
            MailMessage EmailMsg = new MailMessage();

            EmailMsg.To.Add(txtEmail.Text.Trim());
            EmailMsg.From = new MailAddress(txtEmail.Text.Trim());
            EmailMsg.Subject = "Attached Image";
            EmailMsg.Body = "Image is attached!";

            MemoryStream imgStream = new MemoryStream();
            System.Drawing.Image img = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream);
            string filename = fuImage.PostedFile.FileName;

            img.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            EmailMsg..Attachments.Add(new Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg));

            emailClient.Send(EmailMsg);

            lblSent.Visible = true;

        }
    }
}

最佳答案

在我的頭頂,你不需要創建一個Image對象。

更改:

  MemoryStream imgStream = new MemoryStream(); 
  System.Drawing.Image img = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream); 
  string filename = fuImage.PostedFile.FileName; 

  img.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
  EmailMsg..Attachments.Add(new Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg)); 

  //can't remember, but you may also need 至 set the position 至 0 ?
  //fulImage.PostedFile.InputStream.Position = 0
  EmailMsg..Attachments.Add(new Attachment(fulImage.PostedFile.Inputstream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg)); 

此外,這假設您上傳的圖像是JPEG。

轉載註明原文: ASP.NET使用電子郵件發送圖像附件而不保存到文件系統