using System; using System.Data.OracleClient; using System.Net; using System.Net.Mail; using NLog; namespace CCSTrace.CCS.Function { public class MailService { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private SmtpClient _smtpClient; private string _smtpIp; private int _smtpPort; private string _eMailAddr; private string _eMailPass; private string _toEMail; public MailService() { } public void InitialSmtpClient(OracleConnection conn) { GetMailSetting(conn); _smtpClient = new SmtpClient(_smtpIp, _smtpPort) { Credentials = new NetworkCredential(_eMailAddr, _eMailPass), EnableSsl = false }; } public bool SendMail(string ccsid) { Attachment objAttFle = new Attachment(GlobalVariable.CcsListPath + ccsid + ".txt"); MailMessage objMail = new MailMessage(); try { objMail.From = new MailAddress(_eMailAddr); objMail.To.Add(_toEMail); objMail.BodyEncoding = System.Text.Encoding.UTF8; objMail.Subject = "CCS事故案件追蹤失敗"; //objMail.Body = "測試收件者"; objMail.IsBodyHtml = true; objMail.Attachments.Add(objAttFle); _smtpClient.Send(objMail); return true; } catch { return false; } } private void GetMailSetting(OracleConnection conn) { const string sqlStmt = "SELECT MAIL_ACCOUNT,MAIL_PASSWORD,MAIL_HOST,MAIL_PORT,WOS_MAIL FROM USRADMIN.SYS_MAIL"; OracleCommand command = new OracleCommand(sqlStmt, conn); OracleDataReader reader = command.ExecuteReader(); try { if (reader.Read()) { _smtpIp = reader["MAIL_HOST"].ToString(); _smtpPort = Convert.ToInt32(reader["MAIL_PORT"].ToString()); _eMailAddr = reader["MAIL_ACCOUNT"].ToString(); _eMailPass = reader["MAIL_PASSWORD"].ToString(); _toEMail = reader["CCS_MAIL"].ToString(); } } catch (Exception e) { Logger.Error(e, e.Message); } finally { reader.Close(); command.Dispose(); } } } }