C#原生邮件发送+发送日志记录

来源:互联网 发布:js基本数据类型有几种 编辑:程序博客网 时间:2024/06/05 09:11

首先需要两个引用:

using System.Net.Mail;using System.IO;

以下为正文:


public int sendMail(string from, string to, string subject, string body, string host, string username, string password)        {            try            {                int n=0;                MailAddress fromAdd = new MailAddress(from);                MailMessage mail = new MailMessage();                mail.Subject = subject;                mail.From = new MailAddress(from);                mail.Body = body;                mail.BodyEncoding = System.Text.Encoding.UTF8;                mail.IsBodyHtml = true;                mail.Priority = MailPriority.High;                SmtpClient client = new SmtpClient();                client.Host = host;                client.UseDefaultCredentials = false;                client.Credentials = new System.Net.NetworkCredential(username, password);                client.DeliveryMethod = SmtpDeliveryMethod.Network;                string[] toAdd = to.Split(';');                            foreach (string temp in toAdd)                {                    mail.To.Add(new MailAddress(temp));                    client.Send(mail);                    mail.To.Clear();                    n++;                    WriteInfo("发送成功:"+temp);                }                return n;            }            catch (Exception ex)            {                throw ex;            }        }        public void WriteInfo(string errorMessage)        {            try            {                //string pathInfo = ConfigurationManager.AppSettings["ErrorsIn"];                //string ErrorTxtPath = pathInfo.ToString().Trim() + "" + DateTime.Now.ToString("yyyyMMdd") + ".txt";                Directory.CreateDirectory("Log");//创建文件夹                string ErrorTxtPath = "Log" + "/" + DateTime.Now.ToString("yyyyMMdd") + ".txt";                if (!File.Exists(ErrorTxtPath))                {                    using (FileStream fs = File.Create(ErrorTxtPath))                    {                    }                }                StreamWriter writerInfo = new StreamWriter(ErrorTxtPath, true);                string errInfo = DateTime.Now.ToString() + ":工作邮件发送日志:" + errorMessage + "\r\n  ";                writerInfo.Write(errInfo);                writerInfo.Close();            }            catch            {            }        }

原创粉丝点击