更新答:
爲SmtpClient
的文件,在這個答案中使用的類,現在讀,「過時的(「SmtpClient和其類型的網絡設計不當,我們強烈建議您使用https://github.com/jstedfast/MailKit和https://github.com/jstedfast/MimeKit代替」)'。
來源:https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official
原來的答案:
使用MailDefinition類是錯誤的做法。是的,它很方便,但它也很原始,並且依賴於Web UI控件 - 這對於通常是服務器端任務的東西沒有意義。
下面介紹的方法基於MSDN文檔和Qureshi's post on CodeProject.com。
注意:本示例從嵌入式資源中提取HTML文件,圖像和附件,但使用其他替代方法來獲取這些元素的流是很好的,例如,硬編碼的字符串,本地文件等等。
Stream htmlStream = null;
Stream imageStream = null;
Stream fileStream = null;
try
{
// Create the message.
var from = new MailAddress(FROM_EMAIL, FROM_NAME);
var to = new MailAddress(TO_EMAIL, TO_NAME);
var msg = new MailMessage(from, to);
msg.Subject = SUBJECT;
msg.SubjectEncoding = Encoding.UTF8;
// Get the HTML from an embedded resource.
var assembly = Assembly.GetExecutingAssembly();
htmlStream = assembly.GetManifestResourceStream(HTML_RESOURCE_PATH);
// Perform replacements on the HTML file (if you're using it as a template).
var reader = new StreamReader(htmlStream);
var body = reader
.ReadToEnd()
.Replace("%TEMPLATE_TOKEN1%", TOKEN1_VALUE)
.Replace("%TEMPLATE_TOKEN2%", TOKEN2_VALUE); // and so on...
// Create an alternate view and add it to the email.
var altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
msg.AlternateViews.Add(altView);
// Get the image from an embedded resource. The <img> tag in the HTML is:
// <img src="pid:IMAGE.PNG">
imageStream = assembly.GetManifestResourceStream(IMAGE_RESOURCE_PATH);
var linkedImage = new LinkedResource(imageStream, "image/png");
linkedImage.ContentId = "IMAGE.PNG";
altView.LinkedResources.Add(linkedImage);
// Get the attachment from an embedded resource.
fileStream = assembly.GetManifestResourceStream(FILE_RESOURCE_PATH);
var file = new Attachment(fileStream, MediaTypeNames.Application.Pdf);
file.Name = "FILE.PDF";
msg.Attachments.Add(file);
// Send the email
var client = new SmtpClient(...);
client.Credentials = new NetworkCredential(...);
client.Send(msg);
}
finally
{
if (fileStream != null) fileStream.Dispose();
if (imageStream != null) imageStream.Dispose();
if (htmlStream != null) htmlStream.Dispose();
}
這看起來超級陳舊 – Daniel 2013-04-22 15:24:52
這對我來說是最好的答案。簡單和重點(雖然承認非常笨重)。 MailDefinition非常漂亮,但不是我想要的。 – thehelix 2015-09-16 19:28:59
走出你的洞穴男人的歡呼聲! – tobias 2016-03-23 08:51:22