.NET发送邮件代码--測試通過
引入命名空間
using System.Net.Mail;
using System.Net;
private static bool SendMail(string toAddress, string mailSubject, string mailBody)
{
MailAddress from = new MailAddress("xiachufeng@126.com", "xiachufeng"); //设置发件人信箱,及显示名字
MailAddress to = new MailAddress(toAddress, "gangge"); //设置收件人信箱,及显示名字
MailMessage oMail = new MailMessage(from, to); //创建一个MailMessage对象
oMail.Subject = mailSubject; //邮件标题
oMail.Body = mailBody; //邮件内容
oMail.Attachments.Add(new Attachment("D:\\project.rar")); //附件
oMail.IsBodyHtml = true; //指定邮件格式,支持HTML格式
oMail.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");//邮件采用的编码
oMail.Priority = MailPriority.High;//设置邮件的优先级为高
//发送邮件服务器
SmtpClient client = new SmtpClient();
client.Host = "smtp.126.com"; //指定邮件服务器
client.Credentials = new NetworkCredential("xiachufeng@126.com", "你的密码");//指定服务器邮件,及密码
try
{
client.Send(oMail); //发送邮件
}
catch (Exception eall)
{
string str = eall.Message;
return false;
}
finally
{
oMail.Attachments.Dispose();
oMail.Dispose(); //释放资源
}
return true;
}
/// <summary>
/// 调用 发送邮件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
bool b = SendMail("duchenggang.accp@163.com", "你好", "哈哈哈,做个测试gang");
if (b == true)
{
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script>alert('ok')</script>");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script>alert('error')</script>");
}
}