如何在邮件正文消息中包含链接?

时间:2013-11-18 15:39:29

标签: c# .net visual-studio smtp visual-studio-2013

我想发送一封带有超链接的电子邮件,我尝试发送没有链接的电子邮件,但是当我添加链接时出错了

这是代码:

MailMessage o = new MailMessage("f@hotmail.com", "f@hotmail.com", "KAUH Account Activation", "Hello, " + name + "\n Your KAUH Account about to activate click the link below to complete the actination process \n "+<a href=\"http://localhost:49496/Activated.aspx">login</a>);
NetworkCredential netCred = new NetworkCredential("f@hotmail.com", "****");
SmtpClient smtpobj = new SmtpClient("smtp.live.com", 587);
smtpobj.EnableSsl = true;
smtpobj.Credentials = netCred;
smtpobj.Send(o);

6 个答案:

答案 0 :(得分:8)

您需要为MailMessage的正文启用HTML,如下所示:

o.IsBodyHtml = true;

也许您应该选择另一个构造函数,以使代码更具可读性。也许是这样的事情:

var mailMessage = new MailMessage();
mailMessage.From = new MailAddress("sender@domain.com", "Customer Service");
mailMessage.To.Add(new MailAddress("someone@domain.com"));
mailMessage.Subject = "A descriptive subject";
mailMessage.IsBodyHtml = true;
mailMessage.Body = "Body containing <strong>HTML</strong>";

完整文档:http://msdn.microsoft.com/en-us/library/System.Net.Mail.MailMessage(v=vs.110).aspx

<强>更新 看起来你的字符串构建会给你带来麻烦。有时候,当把字符串放在一起(或者在调用时将它们连接起来)时,让所有引号都正确是很棘手的。当创建如电子邮件这样大的字符串时,有一些选项可以使它正确。

首先,常规字符串 - 缺点是难以阅读

string body = "Hello, " + name + "\n Your KAUH Account about to activate click the link below to complete the actination process \n <a href=\"http://localhost:49496/Activated.aspx">login</a>";

第二,逐字字符串 - 允许代码中的换行符提高可读性。注意开头的@字符,引用转义序列从\"更改为""

string body = @"Hello, " + name + "\n Your KAUH Account about to
    activate click the link below to complete the actination process \n 
    <a href=""http://localhost:49496/Activated.aspx"">login</a>"

第三,字符串构建器。在许多方面,这实际上是首选方式。

var body = new StringBuilder();
body.AppendFormat("Hello, {0}\n", name);
body.AppendLine(@"Your KAUH Account about to activate click 
    the link below to complete the actination process");
body.AppendLine("<a href=\"http://localhost:49496/Activated.aspx\">login</a>");
mailMessage.Body = body.ToString();

StringBuilder docs:http://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx

答案 1 :(得分:3)

将邮件标记为html o.IsBodyHtml = true

答案 2 :(得分:3)

     String body = "ur message : <a href='http://www.yoursite.com'></a>"
     o.Body = body;

o.IsBodyHtml = true

答案 3 :(得分:1)

你忘了逃避“:href = \”.... \“&gt;登录

答案 4 :(得分:1)

语法错误:

MailMessage o [...snip...] \n "+<a href=\"http://localh [...snip...]
                              ^--terminates the string
                                ^^^^^^^^^^^^^^--interpreted as code

答案 5 :(得分:0)

string url = lblHidOnlineURL.Value + hidEncryptedEmpCode.Value;
body = hid_EmailBody.Value.Replace("@Compting", "HHH").Replace("@toll", hid_TollFreeNo.Value).Replace("@llnk", "<a style='font-family: Tahoma; font-size: 10pt; color: #800000; font-weight: bold' href='http://" + url + "'>click here To Download</a>");
相关问题