2010-01-20 22 views
16

我有一個要求發送包含文本和圖像的電子郵件。
因此,我有.mhtml文件,其中包含需要通過電子郵件發送的內容。發送mhtml電子郵件 - C#

我爲此使用了奇爾卡特,但在Outlook 2007中,它將mhtml文件顯示爲不同的附件(html +圖像)。

任何人都可以建議我一些其他組件發送mhtml電子郵件。
僅供參考,我正在使用.Net 3.5

此外,我不想在發送它們之前將圖像保存在服務器上。

謝謝!

回答

11

我使用普通老本地MailMessage類。這previous answer可以爲您指出正確的方向

編輯:我建了一個類似的代碼,前一段時間,捕捉外部HTML網頁,解析它的內容,抓住所有外部內容(CSS,圖像等),併發送通過電子郵件,而不保存任何東西在磁盤上。

+0

感謝您的答覆。但在上面的鏈接的帖子是使用LinkedResource需要所有的圖像在物理上保存在服務器上,我不想:-( – iniki 2010-01-20 11:34:13

+1

這並非完全正確:LinkedResource第一個參數是一個流,因此您的圖像可以存儲在一些數據庫,例如 – 2010-01-20 11:51:08

4

以下是使用圖像作爲嵌入資源的示例。

MailMessage message = new MailMessage(); 
message.From = new MailAddress(fromEmailAddress); 
message.To.Add(toEmailAddress); 
message.Subject = "Test Email"; 
message.Body = "body text\nblah\nblah"; 

string html = "<body><h1>html email</h1><img src=\"cid:Pic1\" /><hr />" + message.Body.Replace(Environment.NewLine, "<br />") + "</body>"; 
AlternateView alternate = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html); 
message.AlternateViews.Add(alternate); 

Assembly assembly = Assembly.GetExecutingAssembly(); 
using (Stream stream = assembly.GetManifestResourceStream("SendEmailWithEmbeddedImage.myimage.gif")) { 
    LinkedResource picture = new LinkedResource(stream, MediaTypeNames.Image.Gif); 

    picture.ContentId = "pic1"; // a unique ID 
    alternate.LinkedResources.Add(picture); 

    SmtpClient s = new SmtpClient(); 
    s.Host = emailHost; 
    s.Port = emailPort; 
    s.Credentials = new NetworkCredential(emailUser, emailPassword); 
    s.UseDefaultCredentials = false; 

    s.Send(message); 
} 
} 
+1

當我從Aspose實用程序獲取mhtml輸出時,我無法控制Images的名稱,因此在我的情況下設置ContentId不可行,我認爲這是使用LinkedResource的基礎。 – iniki 2010-01-28 12:33:01

+0

@iniki你不只是預處理HTML內容,並用'cid'引用替換圖像的'src',並使用原始內容(文件名或數據URI)來生成'LinkedResource'? – Keith 2012-12-19 09:59:16

2
System.Net would be the one that you are looking for.<br/> 
MailMessage is used to compose new mail.<br/> 
SMTPClient is used to send mail. 
NetworkCredentials would be used to attach username and password for making request to sending mail. 


來到你的問題如何添加圖像。
您需要設置isHtml=true爲MAILMESSAGE
既然你要發送的郵件的HTML相對路徑將無法正常工作像在這種情況下../directory/imagename.formate
你需要給完成的圖像的路徑位置這是websiteUrl/directory/imagename.formate
要動態地獲取完整的Url,你可以這樣使用Request.Uri.GetLeftParth(URIPartial.Authority)+VitrtualToAbsolute.getAbsolute("~")

我不知道最後一行,因爲我在這裏直接寫了。你只需要使用它,並有良好的運氣;-)

+0

這不會回答如何發送MHTML中嵌入圖像的MHTML電子郵件 – 2012-12-18 15:31:14

0

您需要明確設置爲multipart/related的MIME類型。更改MailMessage.Body以在其中包含MHTML文件的內容。最後,將一個新項目添加到MailMessage.AlternateViews集合中以定義正確的MIME類型。從MSDN下面的鏈接有一個很好的例子,如何對其進行設置:

MailMessage.AlternateViews Property