2014-02-10 69 views
6

是否有任何方法將System.Drawing.Image附加到電子郵件中,然後保存它,然後從保存的路徑中抓取它。C#附加System.Drawing.Image到電子郵件

現在我正在創建圖像並保存它。

MailMessage mail = new MailMessage(); 
       string _body = "body" 

       mail.Body = _body; 
       string _attacmentPath; 
       if (iP.Contains(":")) 
        _attacmentPath = (@"path1");//, System.Net.Mime.MediaTypeNames.Application.Octet)); 
       else 
        _attacmentPath = @"path2"); 
       mail.Attachments.Add(new Attachment(_attacmentPath, System.Net.Mime.MediaTypeNames.Application.Octet)); 
       mail.To.Add(_imageInfo.VendorEmail); 
       mail.Subject = "Rouses' PO # " + _imageInfo.PONumber.Trim(); 
       mail.From = _imageInfo.VendorNum == 691 ? new MailAddress("email", "") : new MailAddress("email", ""); 
       SmtpClient server = null; 
       mail.IsBodyHtml = true; 
       mail.Priority = MailPriority.Normal; 
       server = new SmtpClient("server"); 
       try 
       { 

        server.Send(mail); 
       } 
       catch 
       { 

       } 

反正到System.Drawing.Image對象直接傳遞給mail.Attachments.Add():然後,我發送電子郵件?

回答

12

你不可錯過的Image直接的連接,但你可以通過只圖像保存到MemoryStream,然後提供給MemoryStream附件構造跳過文件系統:

var stream = new MemoryStream(); 
image.Save(stream, ImageFormat.Jpeg); 
stream.Position = 0; 

mail.Attachments.Add(new Attachment(stream, "image/jpg")); 
+0

+1 - 您的代碼比我使用的代碼更加緊湊和乾淨。 =) – OnoSendai

+0

謝謝,這工作,只是讓我幾個trys意識到我不得不添加「.jpg」的名稱參數的末尾! – JustinV

5

理論上,您可以將圖像轉換爲MemoryStream,然後將該流添加爲附件。它會是這樣的:

public static Stream ToStream(this Image image, ImageFormat formaw) { 
    var stream = new System.IO.MemoryStream(); 
    image.Save(stream, formaw); 
    stream.Position = 0; 
    return stream; 
} 

然後你可以用下面的

var stream = myImage.ToStream(ImageFormat.Gif); 

現在,你有流,你可以將其添加爲附件:

mail.Attachments.Add(new Attachment(stream, "myImage.gif", "image/gif")); 

參考:

System.Drawing.Image to stream C#

c# email object to stream to attachment