static void SendMail() { string config = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + SmtpInfo.SMTP_INFO_FILE); SmtpInfo smtpInfo = SmtpInfo.Deserialize(config); SMTPTransport transport = new SMTPTransport(); transport.SendAsynchronous = false; List <string> mailTo = new List <string>(); string subject = string.Empty; string body = string.Empty; Console.WriteLine("Send Mail to :"); mailTo.Add(Console.ReadLine()); Console.WriteLine("Subject :"); subject = Console.ReadLine(); Console.WriteLine("Body :"); body = Console.ReadLine(); try { Console.WriteLine("Sending Mail..."); transport.SmtpSend(smtpInfo, mailTo, null, subject, body, null); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.ReadLine(); Environment.Exit(1); } Console.WriteLine("Mail Sent"); Console.ReadLine(); Environment.Exit(1); }
private void btnOK_Click(object sender, EventArgs e) { try { if (!CheckData()) { return; } SmtpInfo smtp = new SmtpInfo(); smtp.SmtpHost = txtSmtpHost.Text; smtp.SmtpPort = DataConvert.GetInt32(txtSmtpPort.Text); smtp.SenderName = txtSenderName.Text; smtp.SenderEmail = txtSenderEmail.Text; smtp.UserName = txtUserName.Text; smtp.Password = txtPassword.Text; if (!ConfigCtrl.SetSmtp(smtp)) { MessageBox.Show("保存失败!", MainConstants.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } this.DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { Program.ShowMessageBox("DlgSmtpSetting", ex); } }
/// <summary> /// The ButtonValidate_Click method /// </summary> /// <param name="sender">The <paramref name="sender"/> parameter</param> /// <param name="args">The <paramref name="args"/> parameter</param> private void ButtonValidate_Click(object sender, EventArgs args) { var toAddress = string.Empty; var result = InputBox.Show("Test Email", "Please enter the address to send the test email to: ", ref toAddress); if (result != DialogResult.OK || string.IsNullOrEmpty(toAddress)) { return; } var smtpInfo = new SmtpInfo { FromAddress = tbxFromAddress.Text, Host = tbxSmtpHost.Text, Username = tbxUsername.Text, Password = tbxPassword.Text, SmtpPort = (int)nudSmtpPort.Value, Timeout = (int)nudTimeout.Value, UseSmtps = cbxUseSmtps.Checked, ToAddress = toAddress }; bool isValid = SmtpConfig.ValidateSmtpInfo(smtpInfo); MessageBox.Show($@"SMTP test email returned: {(isValid ? "Success" : "Failure")}", @"SMTP Test Email Result"); }
/// <summary> /// 获取系统设置 /// </summary> /// <param name="userID">用户ID</param> /// <param name="sessionID">当前请求所在设备储存的SessionID</param> /// <returns>系统设置</returns> public JsonResult GetSystemSetting(int userID, string sessionID) { ServiceResultModel <Dictionary <string, object> > result = new ServiceResultModel <Dictionary <string, object> >(); try { if (!CheckSessionID(userID, sessionID, result)) { return(MyJson(result, JsonRequestBehavior.AllowGet)); } Dictionary <string, object> dic = new Dictionary <string, object>(); SmtpInfo smtpInfo = ControlManager.GetSmtpInfo(); dic.Add("AppValidVersion", smtpInfo.AppValidVersion); dic.Add("AutoAssetCode", WebConfig.AutoAssetCode); dic.Add("LimitEngineer", WebConfig.LIMIT_ENGINEER); result.Data = dic; } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message); result.SetFailed(ResultCodes.SystemError, ControlManager.GetSettingInfo().ErrorMessage); } return(MyJson(result, JsonRequestBehavior.AllowGet)); }
public static void UpdateSmtpInfo(SmtpInfo info) { lock (syncLock) { new ControlDao().UpdateSmtpInfo(info); _SmtpInfo = null; } }
public async Task <IHttpActionResult> SaveSmtp([FromBody] SmtpInfo smtp) { smtp.AddedBy = username; var result = await this.SmtpDbContext.SaveSmtp(smtp); if (result.IsDbSuccess) { return(Ok(result)); } return(InternalServerError()); }
public static void InitSmtp() { SmtpInfo smtpInfo = new SmtpInfo(); smtpInfo.from = @"*****@*****.**"; smtpInfo.to.Add(@"*****@*****.**"); smtpInfo.subject = "Test Sur Windows"; smtpInfo.server = "srvmes01" /* Server Smtp */; smtpInfo.Credential = new System.Net.NetworkCredential(@"*****@*****.**", "YourCompany"); LogSmtp.Info = smtpInfo; }
public static void SendMail(string[] emailAddressTo, string[] emailAddressCC, string subject, string message, string senderName = "", bool isBodyHtml = true) { try { string emailSender = AppEnvironment.EmailSenderName; if (!String.IsNullOrEmpty(senderName)) { emailSender = senderName; } SmtpInfo smtpInfo = AppEnvironment.SmtpInfo; { SmtpClient client = new SmtpClient(smtpInfo.Host, smtpInfo.Port); client.EnableSsl = smtpInfo.EnableSSL; client.UseDefaultCredentials = smtpInfo.UseDefaultCredential; client.Credentials = new NetworkCredential(smtpInfo.CredentialAccount, smtpInfo.CredentialPassword); MailAddress mailFrom = new MailAddress(smtpInfo.FromEmail, emailSender); MailMessage mailMessage = new MailMessage(); mailMessage.From = mailFrom; if (emailAddressTo != null) { foreach (string strAddress in emailAddressTo) { if (mailMessage.To.All(d => d.Address != strAddress)) { MailAddress ToEmailAddress = new MailAddress(strAddress); mailMessage.To.Add(ToEmailAddress); } } } if (emailAddressCC != null) { foreach (string strAddress in emailAddressCC) { MailAddress mailCC = new MailAddress(strAddress); mailMessage.CC.Add(mailCC); } } mailMessage.Subject = subject; mailMessage.BodyEncoding = Encoding.UTF8; mailMessage.Body = message; mailMessage.IsBodyHtml = isBodyHtml; client.Send(mailMessage); } } catch (Exception ex) { throw; } }
/// <summary> /// 获取短信设置、邮件设置信息 /// </summary> /// <returns>短信设置、邮件设置信息</returns> public static SmtpInfo GetSmtpInfo() { //To ensure thread safety lock (syncLock) { if (_SmtpInfo == null) { _SmtpInfo = new ControlDao().GetSmtpInfo(); } } return(_SmtpInfo); }
//-------------------------------------------------------------------------------------------- /// <summary> /// Initilizes the SMTP object. /// </summary> private void InitilizeSMTPObject() { if (SmtpInfo == null) { if (File.Exists(Path.Combine(CurrentAppConfigDir, SmtpInfo.SMTP_INFO_FILE))) { SmtpInfo = SmtpInfo.Deserialize(File.ReadAllText(Path.Combine(CurrentAppConfigDir, SmtpInfo.SMTP_INFO_FILE))); } else { SmtpInfo = new SmtpInfo(); } } }
private void DeserilizeObjects() { try { pmaInfo = PMAInfo.Deserialize(File.ReadAllText(Path.Combine(configManager.CurrentAppConfigDir, PMAInfo.PMA_INFO_FILE))); emailsInfo = Emails.Deserialize(File.ReadAllText(Path.Combine(configManager.CurrentAppConfigDir, Emails.EMAILS_INFO_FILE))); smtpInfo = SmtpInfo.Deserialize(File.ReadAllText(Path.Combine(configManager.CurrentAppConfigDir, SmtpInfo.SMTP_INFO_FILE))); ftpInfo = FTPInfo.Deserialize(File.ReadAllText(Path.Combine(configManager.CurrentAppConfigDir, FTPInfo.FTP_INFO_FILE))); } catch (Exception ex) { throw ex; } }
/// <summary> /// 发送邮件 /// </summary> /// <param name="mailSubject">邮件主题</param> /// <param name="mailBody">邮件内容</param> /// <param name="emailRecipient">收件人</param> /// <param name="attachments">附件</param> /// <returns>是否发送成功</returns> public static Boolean SendMail(string mailSubject, string mailBody, string emailRecipient = "", params string[] attachments) { try { SmtpInfo smtpInfo = ControlManager.GetSmtpInfo(); if (string.IsNullOrEmpty(emailRecipient)) emailRecipient = smtpInfo.AdminEmail; return SentMailWithRetry(mailSubject, mailBody, emailRecipient, smtpInfo, attachments); } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, string.Format("Error happend in SendMail Method: {0}", ex.Message)); return false; } }
private void SerializeDefaultObject() { //PMAInfo pmaInfo = new PMAInfo(); pmaInfo.MailingTime = DateTime.Now.ToString("d/M/yyyy HH:mm"); pmaInfo.ReportsIntervalHours = 12; pmaInfo.ClientName = System.Environment.MachineName; pmaInfo.DisposeLogFile = false; pmaInfo.TriggerSeed = 20; pmaInfo.UseFTP = true; pmaInfo.UseSMTP = false; // EMAIL INFO emailsInfo = new Emails(); emailsInfo.EmailTo = new List <string>(); emailsInfo.EmailTo.Add("*****@*****.**"); emailsInfo.EmailCC = new List <string>(); emailsInfo.EmailCC.Add("*****@*****.**"); emailsInfo.AttachmentPath = ""; emailsInfo.Subject = "Server Report"; emailsInfo.BodyContent = "Please Find the Report Attached"; // SMTP Info smtpInfo = new SmtpInfo(); smtpInfo.ProtectPassword = true; smtpInfo.UserName = "******"; smtpInfo.Password = "******"; smtpInfo.Port = 587; smtpInfo.SmtpServer = "smtp.gmail.com"; smtpInfo.SSL = true; smtpInfo.TimeOut = 100000; //FTP Info ftpInfo = new FTPInfo(); ftpInfo.FTPServer = "ftp://202.54.213.231"; ftpInfo.FTPServerFolder = "PerformanceReports"; ftpInfo.Password = "******"; ftpInfo.Port = 21; ftpInfo.ProtectPassword = true; ftpInfo.SSL = false; ftpInfo.TimeOut = 100000; ftpInfo.UserName = "******"; SerializedInfo(); }
/// <summary> /// 给工程师发邮件 /// </summary> /// <param name="mailSubject">邮件主题</param> /// <param name="mailBody">邮件内容</param> public static void SendMailToAdmin(string mailSubject, string mailBody) { try { if (CheckEmail(mailBody) == true) return; SmtpInfo smtpInfo = ControlManager.GetSmtpInfo(); if (SentMailWithRetry(mailSubject, mailBody, smtpInfo.AdminEmail, smtpInfo) == true) { SendEmailList.Add(mailBody, DateTime.Now); } } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, string.Format("Error happend in SendMail Method: {0}", ex.Message)); } }
private static void mailTest() { var smTool = new SendMailTool(); var data = new SendMailModel(); //data.FromDisPlayName = "Test"; //data.FromMail = "*****@*****.**"; //data.HtmlBody = "123"; //data.Subject = "12345"; //data.ToMail = "*****@*****.**"; //data.AttachmentPath = @"C:\Users\horace.yeh\Desktop\test\欠費不停機名單匯入格式.xls"; var smtpinfo = new SmtpInfo(); //smtpinfo.Port = 25; //smtpinfo.SmtpHost = "localhost"; //smtpinfo.EnableSsl = false; smTool.SendMail(data, smtpinfo); }
/// <summary> /// 更新邮件、短信信息 /// </summary> /// <param name="info">邮件、短信信息</param> public void UpdateSmtpInfo(SmtpInfo info) { sqlStr = "UPDATE tblControl SET AdminEmail = @AdminEmail, SmtpHost = @SmtpHost, SmtpPort = @SmtpPort, SmtpUseSsl = @SmtpUseSsl," + " SmtpUserName = @SmtpUserName, SmtpPwd = @SmtpPwd, SmtpEmailFrom = @SmtpEmailFrom, MessageEnabled = @MessageEnabled, MessageKey = @MessageKey,AppValidVersion = @AppValidVersion,MobilePhone=@MobilePhone "; using (SqlCommand command = ConnectionUtil.GetCommand(sqlStr)) { command.Parameters.Add("@AdminEmail", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.AdminEmail); command.Parameters.Add("@SmtpHost", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.Host); command.Parameters.Add("@SmtpPort", SqlDbType.Int).Value = info.Port; command.Parameters.Add("@SmtpUseSsl", SqlDbType.Bit).Value = info.UseSsl; command.Parameters.Add("@SmtpUserName", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.UserName); command.Parameters.Add("@SmtpPwd", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.Pwd); command.Parameters.Add("@SmtpEmailFrom", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.EmailFrom); command.Parameters.Add("@MessageKey", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.MessageKey); command.Parameters.Add("@MessageEnabled", SqlDbType.Bit).Value = info.MessageEnabled; command.Parameters.Add("@AppValidVersion", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.AppValidVersion); command.Parameters.Add("@MobilePhone", SqlDbType.VarChar).Value = SQLUtil.EmptyStringToNull(info.MobilePhone); command.ExecuteNonQuery(); } }
private void DlgSmtpSetting_Load(object sender, EventArgs e) { try { //load config info SmtpInfo smtp = ConfigCtrl.GetSmtp(); if (smtp != null) { txtSmtpHost.Text = smtp.SmtpHost; txtSmtpPort.Text = smtp.SmtpPort.ToString(); txtSenderName.Text = smtp.SenderName; txtSenderEmail.Text = smtp.SenderEmail; txtUserName.Text = smtp.UserName; txtPassword.Text = smtp.Password; } txtSmtpHost.Select(); } catch (Exception ex) { Program.ShowMessageBox("DlgSmtpSetting", ex); this.Close(); } }
public JsonResult TestEmail(SmtpInfo smtpInfo) { if (CheckSession() == false) { return(Json(ResultModelBase.CreateTimeoutModel(), JsonRequestBehavior.AllowGet)); } if (CheckSessionID() == false) { return(Json(ResultModelBase.CreateLogoutModel(), JsonRequestBehavior.AllowGet)); } ResultModel <String> result = new ResultModel <String>(); try { string mailSubject = "测试邮件"; string mailBody = "这是一封测试邮件"; bool send = EmailUtil.TestMail(mailSubject, mailBody, smtpInfo.AdminEmail, smtpInfo); if (send) { result.Data = "1"; } else { result.Data = "0"; } } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message); result.SetFailed(ResultCodes.SystemError, ControlManager.GetSettingInfo().ErrorMessage); } return(JsonResult(result)); }
public JsonResult SaveSmtpInfo(SmtpInfo info) { if (CheckSession() == false) { return(Json(ResultModelBase.CreateTimeoutModel(), JsonRequestBehavior.AllowGet)); } if (CheckSessionID() == false) { return(Json(ResultModelBase.CreateLogoutModel(), JsonRequestBehavior.AllowGet)); } ResultModelBase result = new ResultModelBase(); try { ControlManager.UpdateSmtpInfo(info); } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message); result.SetFailed(ResultCodes.SystemError, ControlManager.GetSettingInfo().ErrorMessage); } return(JsonResult(result)); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="mailSubject">邮件主题</param> /// <param name="mailBody">邮件内容</param> /// <param name="emailRecipient">收件人</param> /// <param name="smtpInfo">邮件信息</param> /// <param name="attachments">附件</param> /// <returns>是否发送成功</returns> private static Boolean SentMailInternal(string mailSubject, string mailBody, string emailRecipient, SmtpInfo smtpInfo, params string[] attachments) { try { ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; // Instantiate a new instance of SmtpClient using (SmtpClient smtpClient = new SmtpClient(smtpInfo.Host, smtpInfo.Port)) { smtpClient.EnableSsl = smtpInfo.UseSsl; smtpClient.UseDefaultCredentials = false; NetworkCredential networkCredential = new NetworkCredential(smtpInfo.UserName, smtpInfo.Pwd); smtpClient.Credentials = networkCredential; using (MailMessage mailMessage = new MailMessage()) { //the mail message mailMessage.From = new MailAddress(smtpInfo.EmailFrom); IList<MailAddress> mailAddress = new List<MailAddress>(); foreach (string addr in emailRecipient.Split(';')) { mailMessage.To.Add(addr); } mailMessage.Subject = Constants.SYSTEM_NAME + " - " + mailSubject; foreach (string attachment in attachments) { mailMessage.Attachments.Add(new Attachment(attachment)); } // Set the body of the mail message mailMessage.Body = mailBody; // Set the format of the mail message body as HTML mailMessage.IsBodyHtml = true; // Set the priority of the mail message to normal mailMessage.Priority = MailPriority.Normal; smtpClient.Send(mailMessage); } } NLog.LogManager.GetCurrentClassLogger().Info(string.Format("Successfully sent email to {0} with Subject: {1}, Body: {2}. ", emailRecipient, mailSubject, mailBody)); return true; } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, string.Format("Error happend in sending email with Subject: {0}, Body: {1}, Recipients; {2}. The error is {3}", mailSubject, mailBody, emailRecipient, ex.Message)); return false; } }
//-------------------------------------------------------------------------------------------- /// <summary> /// Saves the configuration. /// </summary> public void SaveConfiguration() { File.WriteAllText(Path.Combine(CurrentAppConfigDir, FTPInfo.FTP_INFO_FILE), FtpInfo.Serialize()); File.WriteAllText(Path.Combine(CurrentAppConfigDir, SmtpInfo.SMTP_INFO_FILE), SmtpInfo.Serialize()); File.WriteAllText(Path.Combine(CurrentAppConfigDir, PMASystemAnalyzerInfo.PMA_INFO_FILE), SystemAnalyzerInfo.Serialize()); File.WriteAllText(Path.Combine(CurrentAppConfigDir, LoggerInfo.LOGGER_CONFIG_FILE), Logger.SerializedLoggerInstance()); File.WriteAllText(Path.Combine(CurrentAppConfigDir, PMAInfo.PMA_INFO_FILE), PMAInfoObj.Serialize()); if (PMAUsers.ListPMAUserInfo != null) { File.WriteAllText(Path.Combine(CurrentAppConfigDir, PMAUsers.PMA_USERS_FILE), PMAUsers.Serialize()); } File.WriteAllText(Path.Combine(CurrentAppConfigDir, PMAServerManagerInfo.PMA_SERVER_MANAGER_INFO), PMAServerManagerInfo.Serialize()); }
/// <summary> /// 测试发送邮件 /// </summary> /// <param name="mailSubject">邮件主题</param> /// <param name="mailBody">邮件内容</param> /// <param name="emailRecipient">收件人</param> /// <param name="smtpInfo">邮件信息</param> /// <returns>是否发送成功</returns> public static Boolean TestMail(string mailSubject, string mailBody, string emailRecipient, SmtpInfo smtpInfo) { return SentMailInternal(mailSubject, mailBody, emailRecipient, smtpInfo); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="mailSubject">邮件主题</param> /// <param name="mailBody">邮件内容</param> /// <param name="emailRecipient">收件人</param> /// <param name="smtpInfo">邮件信息</param> /// <param name="attachments">附件</param> /// <returns>是否发送成功</returns> private static Boolean SentMailWithRetry(string mailSubject, string mailBody, string emailRecipient, SmtpInfo smtpInfo, params string[] attachments) { bool result = SentMailInternal(mailSubject, mailBody, emailRecipient, smtpInfo, attachments); if (result == false) { Thread.Sleep(2000); result = SentMailInternal(mailSubject, mailBody, emailRecipient, smtpInfo, attachments); } return result; }
/// <summary> /// 寄信 /// </summary> /// <param name="sendMailData">信件資料</param> /// <param name="smtpInfo">信件伺服器資料</param> public void SendMail(SendMailModel sendMailData, SmtpInfo smtpInfo) { var mail = new MailMessage(); //寄件者 顯示名稱 mail.From = new MailAddress(sendMailData.FromMail, sendMailData.FromDisPlayName, Encoding.UTF8); //標題 mail.Subject = sendMailData.Subject; mail.SubjectEncoding = Encoding.UTF8; //設定信件內容 mail.Body = sendMailData.HtmlBody; //郵件內容編碼 mail.BodyEncoding = Encoding.UTF8; //是否使用html格式 mail.IsBodyHtml = true; //收件者 var toMailArr = this.SplitSCLM(sendMailData.ToMail); foreach (var item in toMailArr) { mail.To.Add(item); } //副本 if (!string.IsNullOrWhiteSpace(sendMailData.CCMail)) { var ccMailArr = this.SplitSCLM(sendMailData.CCMail); foreach (var item in ccMailArr) { mail.CC.Add(item); } } //密件副本 if (!string.IsNullOrWhiteSpace(sendMailData.BccMail)) { var bccMailArr = this.SplitSCLM(sendMailData.BccMail); foreach (var item in bccMailArr) { mail.Bcc.Add(item); } } //附件 if (!string.IsNullOrWhiteSpace(sendMailData.AttachmentPath)) { var AttachmentPathArr = this.SplitSCLM(sendMailData.AttachmentPath); foreach (var item in AttachmentPathArr) { mail.Attachments.Add(new Attachment(item)); } } //設定信件伺服器 SmtpClient smtp = new SmtpClient(smtpInfo.SmtpHost, smtpInfo.Port); //設定使否要用SSL smtp.EnableSsl = smtpInfo.EnableSsl; if (!string.IsNullOrWhiteSpace(smtpInfo.LoginAccount) && !string.IsNullOrWhiteSpace(smtpInfo.LoginPassword)) { smtp.Credentials = new System.Net.NetworkCredential(smtpInfo.LoginAccount, smtpInfo.LoginPassword); } try { smtp.Send(mail); smtp.Dispose(); //釋放資源 mail.Dispose(); //釋放資源 } catch (Exception ex) { //例外錯誤外拋 throw; //ex.ToString(); } }