一、使用System.Web.Mail命名空间发邮件
在.Net Framework 1.x 我们需要使用 System.Web.Mail 命名空间下的类来进行发送邮件,但是功能比较弱,比如你的邮件服务器需要验证才能发送邮件。当我用VS2008写如下代码时,会出现“System.Web.Mail.MailMessage ”过时的提示。
private void SendMail()
{
System.Web.Mail.MailMessage mailMsg = new System.Web.Mail.MailMessage();
mailMsg.From = "**@**"; //我的邮箱地址
mailMsg.To = “**@**”; //对方的邮箱地址
mailMsg.Subject = "主题";
mailMsg.BodyFormat = System.Web.Mail.MailFormat.Text;
mailMsg.Body = "内容“;
try
{
System.Web.Mail.SmtpMail.Send(mailMsg);
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
二、使用System.Net.Mail 命名空间
.Net Framework 2.0 下,在 System.Net.Mail 命名空间中提供了对邮件操作的支持,他的功能更强大。比如你的邮件服务器需要验证才能发送邮件。
using System.Net.Mail;
private void SendMail(string host)
{
MailAddress from = new MailAddress("**@**"); //我的邮箱地址
MailAddress to = new MailAddress("**@**");//对方的邮箱地址
MailMessage msg = new MailMessage(from, to);
msg.Subject = "主题";
msg.Body = "内容";
SmtpClient client = new SmtpClient(host);
try
{
client.Send(msg);
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}