2011-11-09 18 views
1

我有一個圖像存儲在SQL服務器。我想檢索圖像並將其放入MailMessage對象中,而不是作爲附件文件,而是作爲html正文的一部分。如何插入到郵件消息從數據庫中的圖像

我發現了許多使用本地圖像文件的示例,但是我還沒有發現任何使用數據庫中的圖像。

任何人都知道我可以如何做到這一點在vb.net?

預先感謝您!

哈維爾

+1

參見http://stackoverflow.com/questions/6261956/how-to-embed-an-image-stream-to-mailmessage。雖然它不會從數據庫中提取圖像,但它會向您顯示如何嵌入不是來自本地文件路徑的圖像。你可以結合這段代碼和代碼從數據庫中檢索圖像到一個內存流中 –

回答

0

你必須從數據庫作爲LinkedResource添加圖像。 當您從數據庫中以字節的形式檢索圖像時,可以使用流添加LinkedResource;通過從字節創建一個內存流。

在C#代碼,但我認爲你應該能夠將其轉換爲VB.Net

var view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(text, null, "text/html"); 
var resource = new System.Net.Mail.LinkedResource(new MemoryStream(bytes), mime); 
resource.ContentId = image.Name; 
view.LinkedResources.Add(resource); 
_message.AlternateViews.Add(view); 
+0

非常感謝Ruben ... – Camacho

+0

你知道爲什麼在Gmail帳戶中這張圖片不顯示嗎?,在Outlook中,與其他Internet郵件帳戶配置,圖像顯示正確嗎?...我嘗試插入圖像作爲附件,在這種情況下,Outlook也正確顯示圖像,但在gmail顯示爲附件,不顯示在html身上... – Camacho

0

你必須包括在與imagetag的htmlbody圖像:<img src="cid:myuniqueid" alt="img" />

通過添加LinkedResource可以將圖像包含到消息中。但是你需要在HTML body和圖像之間創建一個鏈接。這是html正文中的「cid:myuniqueid」。 cid的值必須等於LinkedResource對象的ContentID屬性的值。

下面是一個例子:

 '** Create MailMessage Object 
    Dim message As New MailMessage() 

    '** Create HTML view 
    Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(htmlbody, System.Text.Encoding.Default, MediaTypeNames.Text.Html) 

    '** Create resource for the image 
    Dim lr As New LinkedResource(objStream) 

    '** Set the contentid for the image resource 
    lr.ContentId = "myuniqueid" 

    '** Link image resource and htmlview together 
    htmlView.LinkedResources.Add(lr) 

    '** Add view to MailMessage Object 
    message.AlternateViews.Add(htmlView) 
+0

什麼是你的代碼中的「objStream」,你可以插入define語句嗎? – Camacho

相關問題