【C#】新建服务自动发送邮件

---windows服务,
---自动发送邮件

邮件发送code

        #region 发送邮件函数
        public void SendMailUseZj()
        {
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            string[] mailToUsers = ConfigurationManager.AppSettings["mailToUser"].Split(',');
            for (int i = 0; i < mailToUsers.Length - 1; i++)
            {
                msg.To.Add(mailToUsers[i]);
            }
            /*
            * msg.To.Add("b@b.com");
            * msg.To.Add("b@b.com");可以发送给多人
            */
            /*
            * msg.CC.Add("c@c.com");
            * msg.CC.Add("c@c.com");可以抄送给多人
            */
            msg.From = new MailAddress("123456789@qq.com", "啊强", System.Text.Encoding.UTF8);
            /* 上面3个参数分别是发件人地址(可以随便写),发件人姓名,编码*/
            msg.Subject = "这第 “" + i + "” 封测试邮件";//邮件标题   
            msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码   
            msg.Body = "邮件内容" + DateTime.Now;//邮件内容   
            msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码   
            msg.IsBodyHtml = false;//是否是HTML邮件   
            msg.Priority = MailPriority.Normal;//邮件优先级   

            SmtpClient client = new SmtpClient();
            string CredentialsName = ConfigurationManager.AppSettings["mailName"];
            string CredentialsPass = DESencrypt.DesDecrypt(ConfigurationManager.AppSettings["mailPassword"]);
            string CredentialsHost = ConfigurationManager.AppSettings["mailPop3"];
            client.Host = CredentialsHost;
            client.Credentials = new System.Net.NetworkCredential(CredentialsName, CredentialsPass);
           //此行是终点否则会提示 认证错误
            client.EnableSsl = true;

            object userState = msg;
            try
            {
                client.Send(msg);   //client.SendAsync(msg, userState);
                //简单一点儿可以client.Send(msg);   
                InsertLog("发送成功");
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                InsertLog("发送邮件出错" + ex.Message + "--");
            }
        }

 

posted @ 2016-05-19 12:13  oiliu  阅读(1115)  评论(0编辑  收藏  举报