C#原生郵件傳送+傳送日誌記錄

zhang98722發表於2011-10-10

首先需要兩個引用:

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
            {

            }
        }

相關文章