基于.NET2.0的System.Net.Mail发送邮件Demo

第一种:
        //emailaddress邮件接收者地址
        //mailcontent邮件主体内容
        //mailtitle邮件标题
        //mailsubject邮件主题
        public bool SendMail(string emailaddress,string mailcontent,string mailtitle,string mailsubject) {
            MailMessage onemail = new MailMessage();
            string myEmail="aaaa@163.com";  //发送邮件的邮箱地址
            string myPwd="11111111";  //发送邮件的邮箱密码
            onemail.BodyEncoding=System.Text.Encoding.UTF8;
            onemail.IsBodyHtml=true;
            onemail.From = new MailAddress(myEmail);
            onemail.To.Add (new MailAddress(emailaddress)) ;
            onemail.Subject = mailsubject;
            onemail.Body = mailcontent;
            onemail.BodyEncoding = System.Text.Encoding.UTF8;
            SmtpClient clint = new SmtpClient("mail.iapechina.com");//发送邮件的服务器
            clint.UseDefaultCredentials = false;
            clint.Credentials = new System.Net.NetworkCredential(myEmail,myPwd);
            clint.DeliveryMethod = SmtpDeliveryMethod.Network;

            try
            {
                clint.Send(onemail);
                return true;
            }
            catch (Exception ex) {
                return false;
            }   
        }

第二种:

在web.config中做如下设置
<configuration>
<system.net>
    <mailSettings>
       <smtp from="aaaa@163.com"> <!--要发送邮件的邮箱-->
           <network host="mail.iapechina.com" password="1111111" port="25" userName="aaaa@163.com" defaultCredentials="false"/>
      </smtp>
  </mailSettings>
</system.net>
</configuration>

        //emailaddress邮件接收者地址
        //mailcontent邮件主体内容
        //mailtitle邮件标题
        //mailsubject邮件主题
        private bool SendMail(string emailaddress,string mailcontent,string mailtitle,string mailsubject) {
            MailMessage onemail = new MailMessage();
            onemail.BodyEncoding=System.Text.Encoding.UTF8;
            onemail.IsBodyHtml=true;
            onemail.To.Add (new MailAddress(emailaddress)) ;
            onemail.Subject = mailsubject;
            onemail.Body = mailcontent;
            onemail.BodyEncoding = System.Text.Encoding.UTF8;
            SmtpClient clint = new SmtpClient();

            try
            {
                clint.Send(onemail);
                return true;
            }
            catch (Exception ex) {
                return false;
            }   
        }
 
总结:虽然在.NET 2.0下,使用System.Web.Mail发送邮件很简单,在错误的时候也可以得到比较详细的异常信息,但是有时候出现的问题也会让你摸不着头脑。最经常出现的是,当你的机器有安装杀毒防火墙,有可能会发不出邮件,但是提示信息却让你无法诊断是哪里出问题了,大意是邮件发送被拒绝。出现这种事况是由于防火墙拒绝了我们对25端口的使用,从而造成无法与SMTP服务器正常通信。解决办法就是关闭它了,相信网上已经有很多的案例了。还有一点要特别注意,要发送邮件的机器必须是直接外网的,由于公司是通过代理上网,所以这个印象特别深。 上面的代码还有一点需要注意,MailMessage对象的From值必须和配置文件中From值是一样的,这里好像也可以不用设,大家可以试一下。

posted @ 2008-11-04 11:34  Max Woods  阅读(1459)  评论(1编辑  收藏  举报