c#发送邮件功能

需要引用using System.Net.Mail;

 

方法如下:   

public class Mail
    {
        /// <summary>
        /// 发送电子邮件
        /// </summary>
        /// <param name="MessageFrom">发件人邮箱地址</param>
        /// <param name="MessageTo">收件人邮箱地址</param>
        /// <param name="MessageSubject">邮件主题</param>
        /// <param name="MessageBody">邮件内容</param>
        /// <returns></returns>
        public static bool Send(MailAddress MessageFrom, string MessageTo, string MessageSubject, string MessageBody)
        {
            MailMessage message = new MailMessage();
           
            message.From = MessageFrom;
            message.To.Add(MessageTo); //收件人邮箱地址可以是多个以实现群发
            message.Subject = MessageSubject;
            message.Body = MessageBody;
            message.IsBodyHtml = false; //是否为html格式
            message.Priority = MailPriority.High; //发送邮件的优先等级

            SmtpClient sc = new SmtpClient();
            sc.Host = "smtp.163.com"; //指定发送邮件的服务器地址或IP
            sc.Port = 25; //指定发送邮件端口

            //测试账号:zwtest2012@163.com/zwtest20122012 ,随便注册的一个163账号要是自己的可以填自己的
            sc.Credentials = new System.Net.NetworkCredential("zwtest2012@163.com", "zwtest20122012"); //指定登录服务器的用户名和密码(发件人的邮箱登陆密码)

            try
            {
                sc.Send(message); //发送邮件
            }
            catch(Exception ex)
            {
                //throw(ex);
               
                ExcelDBA.WriteLog("----------------------------");//日志小分割
                ExcelDBA.WriteLog("发送邮件到["+MessageTo.ToString()+"]失败!");
                ExcelDBA.WriteLog("错误信息:"+ex.Message.ToString());
                return false;
            }
            return true;

        }


    }

 

调用如下:

protected void Button1_Click(object sender, EventArgs e)
        {
            MailAddress MessageFrom = new MailAddress("zwtest2012@163.com"); //发件人邮箱地址 ,与方法里面的发送账号必须一致
            string MessageTo = "abc@qq.com"; //收件人邮箱地址
            string MessageSubject = "邮件标题标题"; //邮件主题
            string MessageBody = "这里是邮件内容内容内容。"; //邮件内容


            if (Mail.Send(MessageFrom, MessageTo, MessageSubject, MessageBody))
            {
                Response.Write("发送邮件成功111" + DateTime.Now.ToString());
            }
            else
            {
                Response.Write("发送邮件失败222" + DateTime.Now.ToString());
            }

        }

posted @ 2012-04-20 10:58  为乐而来  阅读(1011)  评论(0编辑  收藏  举报