1、新建SMTP.cs类库文件
public class SMTP
{
/// <summary>
/// SMTP服务器
/// </summary>
public string smtp { get; set; }
/// <summary>
/// SMTP服务器端口
/// </summary>
public int port { get; set; }
/// <summary>
/// 发件人
/// </summary>
public string from { get; set; }
/// <summary>
/// 发件人密码
/// </summary>
public string password { get; set; }
/// <summary>
/// 邮件主题
/// </summary>
public string subject { get; set; }
/// <summary>
/// 邮件主题
/// </summary>
public string body { get; set; }
/// <summary>
/// 收件人邮箱
/// </summary>
public string strto { get; set; }
/// <summary>
/// 抄送邮箱
/// </summary>
public List<string> strcc=new List<string>();
/// <summary>
/// 发送邮件
/// </summary>
public void SendMail()
{
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
client.Host = this.smtp;//邮件服务器
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(this.from, this.password);//用户名、密码
client.Port = this.port;
//client.EnableSsl = true;
var msg = new MailMessage();
msg.From = new MailAddress(this.from);
msg.To.Add(strto);
if (this.strcc!=null&& this.strcc.Count>0 )
{
foreach (string OneStrcc in strcc)
{
msg.CC.Add(OneStrcc);
}
}
msg.Subject = subject;//邮件标题
msg.Body = body;//邮件内容
msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码
msg.IsBodyHtml = true;//是否是HTML邮件
msg.Priority = MailPriority.High;//邮件优先级
try
{
client.Send(msg);
}
catch (SmtpException ex)
{
throw ex;
}
}
}
2、使用示例
try
{
var theSMTP = new SMTP
{
smtp = ConfigurationManager.AppSettings["smtp"],
port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]),
from = ConfigurationManager.AppSettings["from"],
password = ConfigurationManager.AppSettings["password"],
subject = "主题",
body = "内容"
};
theSMTP.strto ="xxx@qq.com";
theSMTP.strcc.Add("xxx@qq.com");
theSMTP.SendMail();
}
catch (Exception ex)
{
}