c# email html,在C#中生成HTML电子邮件正文

SmtpClient现在,此答案中使用的类的文档显示为'Obsolete(“ 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在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 tag in the HTML is:

//     

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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值