邮件发送组件
赶在下班之前,发个简单的.net邮件发送组件
1.先添加引入命名空间 System.Net.Mail
2.组件代码:
/// <summary>
/// 邮件发送组件
/// </summary>
public class EmailUtils
{
static EmailUtils() {
MailHost = ConfigurationManager.AppSettings["mailHost"];
MailUserName = ConfigurationManager.AppSettings["mailUserName"];
MailPsw = ConfigurationManager.AppSettings["mailPsw"];
MailFrom = ConfigurationManager.AppSettings["mailFrom"];
}
public static string MailFrom {
get;
set;
}
public static string MailHost {
get;
set;
}
public static string MailUserName {
get;
set;
}
public static string MailPsw {
get;
set;
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="mailto">发送到</param>
/// <param name="title">标题</param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool Send(string mailto, string title, string msg) {
var client = new SmtpClient();
client.Host = MailHost;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(MailUserName, MailPsw);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.Mail.MailMessage message = new MailMessage(MailFrom, mailto);
message.Subject = title;
message.Body = msg;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
try {
client.Send(message);
return true;
}
catch {
return false;
}
}
}
/// 邮件发送组件
/// </summary>
public class EmailUtils
{
static EmailUtils() {
MailHost = ConfigurationManager.AppSettings["mailHost"];
MailUserName = ConfigurationManager.AppSettings["mailUserName"];
MailPsw = ConfigurationManager.AppSettings["mailPsw"];
MailFrom = ConfigurationManager.AppSettings["mailFrom"];
}
public static string MailFrom {
get;
set;
}
public static string MailHost {
get;
set;
}
public static string MailUserName {
get;
set;
}
public static string MailPsw {
get;
set;
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="mailto">发送到</param>
/// <param name="title">标题</param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool Send(string mailto, string title, string msg) {
var client = new SmtpClient();
client.Host = MailHost;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(MailUserName, MailPsw);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.Mail.MailMessage message = new MailMessage(MailFrom, mailto);
message.Subject = title;
message.Body = msg;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
try {
client.Send(message);
return true;
}
catch {
return false;
}
}
}
使用时直接调用 Send 方法即可.
完毕.