发送邮件的方法

来源:百度文库 编辑:神马文学网 时间:2024/04/27 17:16:56
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Mail;//发送邮件的命名空间
//using System.Net.Mail;
using System.Text.RegularExpressions;//regex命名空间

///
///SendEmail 的摘要说明///

public class SendEmail
{
    public SendEmail()
    { }
    public static int F_MailSend(string _strFrom, string _strTo, string _strSubject, string _strBody, string _usename, string _userpwd)
    {
        ///函数作用:发送邮件        ///传入参数:发信人邮箱、收信人邮箱、主题、内容、发信邮箱用户名、发信邮箱密码        ///返 回 值:0为失败;1为成功        //-----验证邮箱的正则表达式------------------------------------------------
        string _strRegex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        MailMessage mail = new MailMessage();
        //验证收件人地址是否正确
        if (!Regex.IsMatch(_strTo, _strRegex))
        {
            return 0;
        }
        else
        {
            mail.To=_strTo;
        }        //验证发件人地址是否正确
        if (!Regex.IsMatch(_strFrom, _strRegex))
        {
            return 0;
        }
        else
        {
            mail.From = _strFrom;
        }        //验证主题是否为空
        if (_strSubject == null || _strSubject == "")
        {
            return 0;
        }
        else
        {
            mail.Subject = _strSubject;
        }        //验证邮件内容是否为空
        if (_strBody == null || _strBody == "")
        {
            return 0;
        }
        else
        {
            mail.Body = _strBody;
        }
        mail.Priority = MailPriority.High; //邮件级别,.High、.Low、.Normal
        mail.BodyFormat = MailFormat.Html; //邮件形式,.Text、.Html
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _usename); //set your username here
        mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _userpwd); //set your password here
        SmtpMail.SmtpServer = "smtp.163.com"; //your real server goes here smtp.163.com
        try
        {
            SmtpMail.Send(mail);
            return 1;
        }
        catch
        {
            return 0;
        }
    }
}