gpt4 book ai didi

c# - 发送预先电子邮件的最佳方式

转载 作者:太空狗 更新时间:2023-10-30 01:06:07 28 4
gpt4 key购买 nike

我想通过 asp.net 发送电子邮件。我使用这段代码,它工作正常。

mail.From = new MailAddress("mail@gmail.com", "sender", System.Text.Encoding.UTF8);
string to = Session["Umail"].ToString();
mail.To.Add(to);
mail.IsBodyHtml = true;

mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = Encoding.GetEncoding("utf-8");
mail.Subject = "subject";
mail.Body = "body" ;
SmtpClient smtp = new SmtpClient("Smtp.gmail.Com", 587);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("mail@gmail.com", "pass"); smtp.Send(mail);

但我想要一封定制的精美邮件。就像从 facebook、google 团队等发送的电子邮件一样。我知道可以在 mail.Body 中使用 html 标签,但这是好方法吗?什么是最好的方法?

最佳答案

这是准备好使用的代码片段,我用它来发送包含文本内容和基于 html 模板的内容的电子邮件:

        // first we create a plain text version and set it to the AlternateView
// then we create the HTML version
MailMessage msg = new MailMessage();

msg.From = new MailAddress("from@email", "From Name");
msg.Subject = "Subject";
msg.To.Add("to@email");
msg.BodyEncoding = Encoding.UTF8;

String plainBody = "Body of plain email";

//first we create the text version
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
msg.AlternateViews.Add(plainView);

//now create the HTML version
MailDefinition message = new MailDefinition();
message.BodyFileName = "~/MailTemplates/template1.htm";
message.IsBodyHtml = true;
message.From = "from@email";
message.Subject = "Subject";

//Build replacement collection to replace fields in template1.htm file
ListDictionary replacements = new ListDictionary();
replacements.Add("<%USERNAME%>", "ToUsername");//example of dynamic content for Username

//now create mail message using the mail definition object
//the CreateMailMessage object takes a source control object as the last parameter,
//if the object you are working with is webcontrol then you can just pass "this",
//otherwise create a dummy control as below.
MailMessage msgHtml = message.CreateMailMessage("to@email", replacements, new LiteralControl());

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");

//example of a linked image
LinkedResource imgRes = new LinkedResource(Server.MapPath("~/MailTemplates/images/imgA.jpg"), System.Net.Mime.MediaTypeNames.Image.Jpeg);
imgRes.ContentId = "imgA";
imgRes.ContentType.Name = "imgA.jpg";
imgRes.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imgRes);

msg.AlternateViews.Add(htmlView);

//sending prepared email
SmtpClient smtp = new SmtpClient();//It reads the SMPT params from Web.config
smtp.Send(msg);

这些是 html 模板的关键部分:

<p>Username: <%USERNAME%></p>

<img src="cid:imgA"/>

关于c# - 发送预先电子邮件的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16373692/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com