我发现这个小代码可以向gmail用户发送电子邮件.我希望邮件的正文包含html(例如,解码链接以使其保存与其指向的URL不同的文本).
我使用的是c#.net 3.5.我在我的代码中使用了这些类:
如何才能做到这一点?
这是我的代码的副本:
MailMessage message = new MailMessage("me@gmail.com", WebCommon.UserEmail, "Test", context.Server.HtmlEncode("<html> <body> <a href='www.cnn.com'> test </a> </body> </html> "));
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("him@gmail.com", "myPwd");
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Port = 587;
smtp.Send(message);
Run Code Online (Sandbox Code Playgroud)
谢谢!
这样的事情应该有效:
注意MailMessage指的是System.Net.MailMessage.还有System.Web.MailMessage,我从未使用过 - 据我所知 - 已经过时了.
MailMessage message = new MailMessage();
// Very basic html. HTML should always be valid, otherwise you go to spam
message.Body = "<html><body><p>test</p></body></html>";
// QuotedPrintable encoding is the default, but will often lead to trouble,
// so you should set something meaningful here. Could also be ASCII or some ISO
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
// No Subject usually goes to spam, too
message.Subject = "Some Subject";
// Note that you can add multiple recipients, bcc, cc rec., etc. Using the
// address-only syntax, i.e. w/o a readable name saves you from some issues
message.To.Add("someone@gmail.com");
// SmtpHost, -Port, -User, -Password must be a valid account you can use to
// send messages. Note that it is very often required that the account you
// use also has the specified sender address associated!
// If you configure the Smtp yourself, you can change that of course
SmtpClient client = new SmtpClient(SmtpHost, SmtpPort) {
Credentials = new NetworkCredential(SmtpUser, SmtpPassword),
EnableSsl = enableSsl;
};
try {
// It might be necessary to enforce a specific sender address, see above
if (!string.IsNullOrEmpty(ForceSenderAddress)) {
message.From = new MailAddress(ForceSenderAddress);
}
client.Send(message);
}
catch (Exception ex) {
return false;
}
Run Code Online (Sandbox Code Playgroud)
对于更复杂的模板解决方案来渲染Body html而不是硬编码,例如,EMailTemplateServiceMvcContrib可以作为指导使用.
| 归档时间: |
|
| 查看次数: |
10504 次 |
| 最近记录: |