private void buttonTestConnect_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxPassword.Text)) { MessageBox.Show("密码不能为空!"); return; } var message = new MimeMailMessage(); message.From = new MimeMailAddress(textBoxAccount.Text); message.To.Add(textBoxAccount.Text); message.Subject = "测试邮件"; message.SubjectEncoding = Encoding.UTF8; message.Body = @"这是在测试你的帐户设置时 Send SMTP 自动发送的电子邮件。"; int.TryParse(textBoxPort.Text, out int port); var mailer = new MimeMailer(textBoxsmpt.Text, port); mailer.User = textBoxAccount.Text; mailer.Password = textBoxPassword.Text; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; mailer.SendCompleted += AsyncaccountConfigEvent; mailer.SendMailAsync(message); }
/// <summary> /// 发送激活邮件 /// </summary> /// <param name="addresser">发件人地址</param> /// <param name="addressPsswd">发件人密码</param> /// <param name="recipient">收件人地址</param> /// <param name="VerifyCode">随机验证码</param> public static void SSLMailSend(string addresser, string addressPsswd, string recipient, string VerifyCode) { try { var msg = new MimeMailMessage(); msg.From = new MimeMailAddress(addresser, "深圳凯华技术有限公司"); msg.To.Add(recipient); msg.Subject = "深圳凯华技术有限公司"; ////邮件正文 StringBuilder Content = new StringBuilder(); Content.Append("请进行邮箱验证,点击下面的链接激活您的邮箱,10分钟内有效:<br><a target='_blank' rel='nofollow' style='color: #0041D3; text-decoration: underline' href=http://120.78.49.234/MerchantPlatformApi/v/" + VerifyCode + ">点击这里</a>"); msg.Body = Content.ToString(); var mailer = new MimeMailer("smtp.mxhichina.com", 465); mailer.User = "******"; mailer.Password = "******"; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; mailer.SendCompleted += compEvent; // mailer.SendMailAsync(msg); mailer.SendMail(msg); } catch (MissingMethodException ex) { Console.WriteLine(ex.ToString()); } }
private static void SendEmail(MainSettings mainSettings, string bodyFile, IEnumerable <string> attachments) { using (var client = new SmtpSocketClient()) { var message = new MimeMailMessage { From = new MimeMailAddress(mainSettings.Mail.From), IsBodyHtml = true, Body = File.ReadAllText(bodyFile), Subject = mainSettings.Mail.Subject }; var toAddresses = mainSettings.Mail.To.Select(x => new MimeMailAddress(x)); message.To.AddRange(toAddresses); var mailAttachments = attachments.Select(x => new MimeAttachment(x)); message.Attachments.AddRange(mailAttachments); client.Host = mainSettings.Mail.SmtpServer; client.Port = 465; client.User = mainSettings.Mail.SmtpLogin; client.Password = mainSettings.Mail.SmtpPass; client.SslType = SslMode.Ssl; client.AuthenticationMode = AuthenticationType.Base64; client.SendMail(message); } }
public void SendMail(string sender, string senderEmail, string mailTo, string mailcc, string subject, string body, string smtpServer, string fromEmail, string displayName, string userName, string password, int port, bool enableSsl) { var message = new MimeMailMessage(); message.To.Add(mailTo); if (!string.IsNullOrEmpty(mailcc)) { message.CC.Add(mailcc); } message.Subject = subject; message.Body = body; //string.Format("<p>{0}</p><p>发件人:{1} ({2}), 发件人邮箱:{3}</p>", body, name, phone, from); message.IsBodyHtml = true; message.ReplyToList.Add(new MailAddress(senderEmail, sender)); //if (!string.IsNullOrEmpty(mailcc)) // message.ReplyToList.Add(new MailAddress(mailTo, sender)); message.Sender = new MailAddress(fromEmail, displayName); message.From = new MailAddress(fromEmail, displayName); SmtpClient smtpClient = new SmtpClient(smtpServer, port) { UseDefaultCredentials = true, EnableSsl = enableSsl, // smtpClient.Port = SettingsManager.SMTP.Port; DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential(userName, password) }; smtpClient.Send(message); }
/// <project>Lettera22</project> /// <copyright company="Claudio Tortorelli"> /// Copyright (c) 2018 All Rights Reserved /// </copyright> /// <author>Claudio Tortorelli</author> /// <email>[email protected]</email> /// <web>http://www.claudiotortorelli.it</web> /// <date>Nov 2018</date> /// <summary> /// /// https://msdn.microsoft.com/it-it/library/system.net.mail.smtpclient(v=vs.110).aspx /// </summary> /// https://choosealicense.com/licenses/mit/ public static void Send(string toAddress, string fromAddress, string subject, string bodyText, string attachmentPath = "") { Globals.m_Logger.Info(toAddress); Globals.m_Logger.Info(fromAddress); Globals.m_Logger.Info(subject); Globals.m_Logger.Info(bodyText); //Generate Message var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(fromAddress); mailMessage.To.Add(toAddress); mailMessage.Subject = subject; mailMessage.Body = bodyText; if (attachmentPath.Length > 0 && File.Exists(attachmentPath)) { MimeAttachment attachMessage = new MimeAttachment(attachmentPath); mailMessage.Attachments.Add(attachMessage); } //Create Smtp Client var mailer = new MimeMailer(Globals.SMTPHost(), Globals.SMTPPort()); mailer.User = Globals.SMTPUsername(); mailer.Password = Globals.SMTPPassword(); mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back mailer.SendCompleted += compEvent; mailer.SendMail(mailMessage); }
private static MimeMailMessage getMimeMailMessage(EmailSettingInfo emailSetting, EmailInfo email, String emailBodyOrg, List <MailAddress> mailList) { String companyName = email.CompanyName.Split('|')[0].Split(':')[0].Trim(); email.CompanyName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(companyName.ToLower()); String emailBody = emailBodyOrg.Replace("{Company}", email.CompanyName).Replace("\r\n", "<br />"); MimeMailMessage mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress("*****@*****.**"); mailMessage.Subject = emailSetting.Subject; mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.IsBodyHtml = true; mailMessage.Body = emailBody; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(emailBody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(emailBody, null, "text/html"); mailMessage.AlternateViews.Add(plainView); mailMessage.AlternateViews.Add(htmlView); foreach (MailAddress emailAddress in mailList) { mailMessage.To.Add(emailAddress); } return(mailMessage); }
public static void SendEmail( string bookName, string strFooters, ref PackageHtml data, ref AccountData ac) { if (string.IsNullOrEmpty(bookName) || data.employeeData.Count == 0) { System.Windows.Forms.MessageBox.Show("没有数据可以发送!"); return; } //Create Smtp Client var mailer = new MimeMailer(ac.StrSMTP, ac.IPort); mailer.User = ac.StrUserName; mailer.Password = ac.StrPassword; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; string footersstr = System.Text.RegularExpressions.Regex.Replace(strFooters, "[\r\n]", "<br>"); foreach (PackageHtml.Employee str in data.employeeData) { //Generate Message var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(ac.StrUserName); mailMessage.To.Add(str.email); mailMessage.SubjectEncoding = Encoding.BigEndianUnicode; mailMessage.Subject = bookName; mailMessage.Body = str.data + footersstr; mailer.SendCompleted += AsynCompleteEvent; mailer.SendMail(mailMessage); } }
public static void EmailSend(string mail, string subject, string body) { var host = "smtp.gmail.com"; var user = "******"; var pass = "******"; //Generate Message var mymessage = new MimeMailMessage(); mymessage.From = new MimeMailAddress(mail); mymessage.To.Add(mail); mymessage.Subject = subject; mymessage.Body = body; //Create Smtp Client var mailer = new MimeMailer(host, 465); mailer.User = user; mailer.Password = pass; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back // mailer.SendCompleted += compEvent; try { mailer.SendMailAsync(mymessage); } catch (Exception ex) { Console.WriteLine(ex.Message); throw ex; } }
} // loadTemplate private void sendReferralReportEmail(Client client, string reportEmail, bool sendToClient) { var poRepo = new ProjectOrganisationRepository(); var project = poRepo.FindProject(client.ProjectId); var staff = poRepo.FindStaffMember(User.Identity.Name); var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(project.Address.Email); if (sendToClient) { mailMessage.To.Add(new MailAddress(client.Address.Email)); } if (staff.Email != null && staff.Email.Length != 0) { mailMessage.To.Add(new MailAddress(staff.Email)); } mailMessage.Subject = "Referral Report for " + client.Name; mailMessage.Body = reportEmail; mailMessage.IsBodyHtml = true; var smtpClient = smtpSender(); smtpClient.Send(mailMessage, SendCompletedEventHandler); }
public static void SendEmailMime(string mailTo, string mailSubject, string mailContent, SendCompletedEventHandler sendCompleted = null) { // 设置发送方的邮件信息,例如使用网易的smtp string smtpServer = ConfigurationManager.AppSettings["SmtpServer"]; // SMTP服务器 string mailFrom = ConfigurationManager.AppSettings["MailFrom"]; // 登陆用户名 string userPassword = ConfigurationManager.AppSettings["MailPassword"]; //登陆密码 //Generate Message var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(mailFrom); mailMessage.To.Add(mailTo); mailMessage.Subject = mailSubject; mailMessage.Body = mailContent; //Create Smtp Client var mailer = new MimeMailer(smtpServer, 465); mailer.User = mailFrom; mailer.Password = userPassword; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back if (sendCompleted != null) { mailer.SendCompleted += sendCompleted; } mailer.SendMail(mailMessage); }
private void SendAim() { //Generate Message var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(textBox1.Text); mailMessage.To.Add(textBox5.Text); mailMessage.Subject = "环都测试邮件"; mailMessage.Body = "环都测试邮件"; //Create Smtp Client var mailer = new MimeMailer(textBox3.Text, Convert.ToInt32(textBox4.Text)); mailer.User = textBox1.Text; mailer.Password = textBox2.Text; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back //mailer.SendCompleted += compEvent; //mailer.SendMailAsync(mailMessage); try { mailer.Send(mailMessage); //client.SendAsync(msg, null); System.Windows.Forms.MessageBox.Show("发送成功"); //Console.WriteLine("发送成功"); } catch (System.Net.Mail.SmtpException ex) { System.Windows.Forms.MessageBox.Show("发送失败"); //Console.WriteLine(ex.Message, "发送邮件出错"); } }
public static void SendEmail(string subject, string message, string userTo) { try { subject = UtilClass.RemoveSign4VietnameseString(subject); userTo = userTo.ToLower(); //Generate Message if (userName.Count() == 0 || string.IsNullOrEmpty(host)) { return; } var mailMessage = new MimeMailMessage(); string smtpUserName = userName[UtilClass.GetRandomNumber(0, userName.Count() - 1)]; mailMessage.From = new MimeMailAddress(smtpUserName); mailMessage.To.Add(userTo); mailMessage.IsBodyHtml = true; mailMessage.Subject = subject; mailMessage.Body = message; //Create Smtp Client var mailer = new MimeMailer(host, port); mailer.User = smtpUserName; mailer.Password = password; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back mailer.SendCompleted += compEvent; mailer.SendMailAsync(mailMessage); } catch (Exception ex) { LogClass.SaveError("ERROR SendEmail: " + ex); } }
public static int?SendNotificationGlobal(string EmailTo, string Subject, string MessageContent, string ParamConfig) { int?status = 1; try { //var dbMAILCONFIG = Common.getSysParam(ParamConfig); string[] config = ParamConfig.Split(new char[] { '|' }); int port = Convert.ToInt16(config[1]); string Security = config[5]; if (!string.IsNullOrEmpty(EmailTo)) { var mymessage = new MimeMailMessage(); mymessage.From = new MimeMailAddress(config[2]); mymessage.To.Add(EmailTo); mymessage.Subject = Subject; mymessage.Body = MessageContent; mymessage.Priority = System.Net.Mail.MailPriority.High; var mailer = new MimeMailer(config[0], port); mailer.User = config[3]; mailer.Password = GeneralCommon.Decrypt(config[4]); if (Security == "TLS") { mailer.SslType = SslMode.Tls; } else if (Security == "SSL") { mailer.SslType = SslMode.Ssl; } else if (Security == "NONE") { mailer.SslType = SslMode.Ssl; } else { mailer.SslType = SslMode.Auto; } if (mailer.SslType == SslMode.None) { mailer.AuthenticationMode = AuthenticationType.PlainText; } else { mailer.AuthenticationMode = AuthenticationType.Base64; } mailer.SendCompleted += compEvent; mailer.SendMail(mymessage); status = 0; } } catch (Exception ex) { status = -1; //UIException.LogException(ex, "public static long SendNotification(string EmailTo,string Subject,string MessageContent)"); } return(status); }
private AbstractMailMessage CreateMessage(string mail, string subject, string body) { var mymessage = new MimeMailMessage(); mymessage.From = new MimeMailAddress(Properties.Settings.Default.smtpUser); mymessage.To.Add(mail); mymessage.Subject = subject; mymessage.Body = body; return(mymessage); }
private void SendEmail() { //Create message mymessage = new MimeMailMessage(); mymessage.From = new MimeMailAddress(mail); mymessage.To.Add(mail); mymessage.Subject = "test"; mymessage.Body = "body"; //Set a delegate function for call back mailer.SendCompleted += compEvent; mailer.SendMailAsync(mymessage); }
public static void SendEMail(MailArguments mailArgs, List <MimeAttachment> attachments, bool isSsl, Dictionary <string, string> headers) { var networkCredential = new NetworkCredential { Password = mailArgs.Password, UserName = mailArgs.MailFrom }; var mailMsg = new MimeMailMessage { Body = mailArgs.Message, Subject = mailArgs.Subject, IsBodyHtml = true // This indicates that message body contains the HTML part as well. }; mailMsg.To.Add(mailArgs.MailTo); if (headers.IsNotNullOrEmpty()) { foreach (var header in headers) { mailMsg.Headers.Add(header.Key, header.Value); } } if (attachments.IsNotNull()) { foreach (var attachment in attachments) { if (attachment.IsNotNull()) { mailMsg.Attachments.Add(attachment); } } } mailMsg.From = new MimeMailAddress(mailArgs.MailFrom); var mailer = new MimeMailer(mailArgs.SmtpHost, Convert.ToInt32(mailArgs.Port)); mailer.User = mailArgs.MailFrom; mailer.Password = mailArgs.Password; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; mailer.SendMailAsync(mailMsg); }
public void EnviarEmailSSLImplicito(string email, string body, string sub, string rutaAdjunto) { var from = "*****@*****.**"; var host = "mail.tagor.cl"; var user = "******"; var pass = "******"; //Generate Message var mymessage = new MimeMailMessage(); mymessage.From = new MimeMailAddress(from); String[] AMailto = email.Split(';'); foreach (String mail in AMailto) { mymessage.To.Add(new MailAddress(mail)); } mymessage.Subject = sub; mymessage.Body = body; mymessage.SubjectEncoding = System.Text.Encoding.UTF8; mymessage.HeadersEncoding = System.Text.Encoding.UTF8; mymessage.IsBodyHtml = true; mymessage.Priority = MailPriority.High; if (rutaAdjunto != string.Empty) { MimeAttachment adj = new MimeAttachment(System.Web.HttpContext.Current.Server.MapPath(rutaAdjunto)); mymessage.Attachments.Add(adj); } //Create Smtp Client var mailer = new MimeMailer(host, 465); mailer.User = user; mailer.Password = pass; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back mailer.SendCompleted += compEvent; mailer.SendMailAsync(mymessage); }
public static void SendReport(string subject, string message) { try { subject = UtilClass.RemoveSign4VietnameseString(subject); var userTo = mailReport.Split(',').ToList(); for (int i = 0; i < userTo.Count; i++) { //Generate Message if (userName.Count() == 0) { return; } var mailMessage = new MimeMailMessage(); string smtpUserName = userName[UtilClass.GetRandomNumber(0, userName.Count() - 1)]; mailMessage.From = new MimeMailAddress(smtpUserName); mailMessage.To.Add(userTo[i]); mailMessage.IsBodyHtml = true; mailMessage.Subject = ServerType + " " + subject; mailMessage.Body = message; //Create Smtp Client var mailer = new MimeMailer(host, port); mailer.User = smtpUserName; mailer.Password = password; if (SSL == "true") { mailer.SslType = SslMode.Ssl; } else { mailer.SslType = SslMode.None; } mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back mailer.SendCompleted += compEvent; mailer.SendMailAsync(mailMessage); } } catch (Exception ex) { LogClass.SaveError("ERROR SendReport: " + ex); } }
private static bool sendingEmailAIM(EmailSettingInfo emailSetting, EmailInfo email, String emailBodyOrg, List <MailAddress> mailList) { Boolean success = false; MimeMailMessage mailMessage = getMimeMailMessage(emailSetting, email, emailBodyOrg, mailList); MimeMailer mailer = getMimeMailer(); System.IO.StreamWriter sw = Utilities.Utilities.CloseConsole(); try { mailer.SendMail(mailMessage); success = true; } catch (Exception ex) { email.Comments = ex.Message; } Utilities.Utilities.OpenConsole(sw); return(success); }
private static void SendEmail(string subject, string message) { //Generate Message var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(mailAddress); mailMessage.To.Add(userTo); mailMessage.Subject = subject; mailMessage.Body = message; //Create Smtp Client var mailer = new MimeMailer(host, 465); mailer.User = userName; mailer.Password = password; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back mailer.SendCompleted += compEvent; mailer.SendMailAsync(mailMessage); }
public static void SendMail(MailUtilParaModel para, MailMessageModel message) { //Generate Message var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(para.MailAddress); //para.ReciverAddressList.ForEach(f=>mailMessage.To.Add(f)); mailMessage.To.Add(para.ReciverAddresses); mailMessage.Subject = message.Subject; mailMessage.Body = message.Text; //Create Smtp Client var mailer = new MimeMailer(para.ServerHost, para.ServerPort); mailer.User = para.LogonUserName; mailer.Password = para.Password; mailer.SslType = (SslMode)para.SSLType; mailer.AuthenticationMode = AuthenticationType.Base64; mailer.SendMailAsync(mailMessage); }
static void SendMail(SendMailConfig config, SendMailContext context) { var client = new SmtpSocketClient(config.Smtp, config.Port, config.From, config.Password); client.SslType = config.SslEnabled ? SslMode.Ssl : SslMode.Auto; var mail = new MimeMailMessage(); mail.From = new System.Net.Mail.MailAddress(context.DisplayName ?? config.From); mail.Sender = new System.Net.Mail.MailAddress(config.From); mail.To.Add(context.To); mail.IsBodyHtml = context.IsBodyHtml; mail.Subject = context.Subject; mail.Body = context.Body; mail.BodyEncoding = Encoding.UTF8; foreach (var attachment in context.Attachments) { mail.Attachments.Add(new MimeAttachment(attachment)); } client.SendMail(mail); }
public static void SendEmail(string subject, string body) { //Generate Message var mailMessage = new MimeMailMessage(); mailMessage.From = new MimeMailAddress(Setting.emailParameter.From); mailMessage.To.Add(Setting.emailParameter.To); mailMessage.Subject = subject; mailMessage.Body = body; //Create Smtp Client var mailer = new MimeMailer(Setting.emailParameter.SMTPServer, Setting.emailParameter.Port); mailer.User = Setting.emailParameter.From; mailer.Password = Setting.emailParameter.Password; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; //Set a delegate function for call back mailer.SendCompleted += compEvent; mailer.SendMailAsync(mailMessage); }
public void SendMessage(Guid messageId, string recipientEmail, string subject, string text) { var message = new MimeMailMessage { From = new MimeMailAddress(_address), Subject = subject, Body = text, IsBodyHtml = true, DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.Delay, To = { recipientEmail }, Headers = { { Constants.MessageIdHeader, messageId.ToString() } }, BodyEncoding = Encoding.Unicode }; _smtpClient.SendCompleted += mailer_SendCompleted; _smtpClient.SendMail(message); }
public void SendEmail(string body, string subject, string address) { string mail = "*****@*****.**"; string pass = "******"; string host = "smtp.ukr.net"; //Generate Message var mymessage = new MimeMailMessage(); mymessage.From = new MimeMailAddress(mail); mymessage.To.Add(address); mymessage.Subject = subject; mymessage.Body = body; //Create Smtp Client var mailer = new MimeMailer(host, 465); mailer.User = mail; mailer.Password = pass; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; mailer.SendMailAsync(mymessage); }
static bool DataReceived(string ipPort, byte[] data) { Regex _re = new Regex(@"^(?<PRI>\<\d{1,3}\>)?(?<HDR>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s[0-3][0-9]\s[0-9]{4}\s[0-9]{2}\:[0-9]{2}\:[0-9]{2}\s[^ ]+?\s)?:\s(?<MSG>.+)?", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.Compiled); Match m = _re.Match(Encoding.UTF8.GetString(data)); if (m.Success) { Message msg = new Message(); if (m.Groups["PRI"].Success) { string pri = m.Groups["PRI"].Value; int priority = Int32.Parse(pri.Substring(1, pri.Length - 2)); msg.Facility = (FacilityType)Math.Floor((double)priority / 8); msg.Severity = (SeverityType)(priority % 8); } else { msg.Facility = FacilityType.User; msg.Severity = SeverityType.Notice; } if (m.Groups["HDR"].Success) { string hdr = m.Groups["HDR"].Value.TrimEnd(); int idx = hdr.LastIndexOf(' '); msg.Datestamp = DateTime.ParseExact(hdr.Substring(0, idx), "MMM dd yyyy HH:mm:ss", null); msg.Hostname = hdr.Substring(idx + 1); } else { msg.Datestamp = DateTime.Now; } msg.Content = m.Groups["MSG"].Value; msg.RemoteIP = ipPort; msg.LocalDate = DateTime.Now; if (MessageReceived != null) { MessageReceived(msg); Dictionary <string, object> d1 = new Dictionary <string, object>(); d1.Add("host", msg.Hostname); d1.Add("facility", msg.Facility); d1.Add("severity", msg.Severity); d1.Add("date", msg.Datestamp); d1.Add("msg", msg.Content); Settings.Sql.Insert("logs", d1); try { //Generate Message var mymessage = new MimeMailMessage(); mymessage.From = new MimeMailAddress(Properties.Settings.Default.mailfrom); mymessage.To.Add(Properties.Settings.Default.mailto); mymessage.Subject = "ASA Log - " + msg.Hostname + " - " + msg.Severity; mymessage.Body = Encoding.UTF8.GetString(data); //Create Smtp Client var mailer = new MimeMailer(Properties.Settings.Default.mailserver, Properties.Settings.Default.mailport); mailer.User = Properties.Settings.Default.mailusername; mailer.Password = Properties.Settings.Default.mailpassword; mailer.SslType = SslMode.Ssl; mailer.AuthenticationMode = AuthenticationType.Base64; mailer.SendMailAsync(mymessage); } catch (Exception ep) { MessageBox.Show(ep.Message, "Failed to send email with the following error:", MessageBoxButtons.OK); } } } return(true); }
public void SendMail(string from, string to, string subject, string body, string cc = null, string bcc = null, Attachment[] attachments = null, string smtpServer = null, string smtpUserName = null, string smtpPassword = null, int smtpServerPortNumber = -1, bool removeCurrentUser = false, string currentUserEmail = null) { ErrorMailSending errorMailSending = new ErrorMailSending(); var myMessage = new MimeMailMessage(); myMessage.BodyEncoding = Encoding.UTF8; myMessage.SubjectEncoding = Encoding.ASCII; //var myMessage = new MailMessage(); myMessage.From = new MailAddress(from); if (removeCurrentUser) { to = RemoveCurrentUser(currentUserEmail, to); cc = RemoveCurrentUser(currentUserEmail, cc); bcc = RemoveCurrentUser(currentUserEmail, bcc); } var debugMailReceiver = Convert.ToString(registryReader.GetHKLMValue("SOFTWARE\\BB", "DebugMailReceiver")); if (string.IsNullOrEmpty(debugMailReceiver)) { debugMailReceiver = Properties.Settings.Default.TestMails; } if (string.IsNullOrEmpty(debugMailReceiver)) { debugMailReceiver = null; } #if DEBUG try { myMessage.To.Add(registryReader.GetValue("HKEY_CURRENT_USER\\BB", "DebugMailReceiver").ToString()); } catch (Exception ex) { string m1 = string.Format("Email is not valid"); string m2 = string.Format("E-mail must be supplied ([email protected])"); string message = string.Format("{0} Error in sending mail to: {1} {2}", ex, to, Properties.Settings.Default.DebugMailReceiver.IsEmpty() ? m2 : m1); throw new Exception(message); } #else var toAddress = debugMailReceiver ?? to; //EventLog.WriteEntry("asaq2back", $"Adding to address: {toAddress} to: {to} len: {to.Length} DebugMailReceiver: {debugMailReceiver} len: {debugMailReceiver?.Length} "); myMessage.To.Add(toAddress); #endif if (!string.IsNullOrEmpty(cc)) { #if !DEBUG myMessage.CC.Add(debugMailReceiver ?? cc); #endif } if (!string.IsNullOrEmpty(bcc)) { #if !DEBUG myMessage.Bcc.Add(debugMailReceiver ?? bcc); #endif } myMessage.Subject = subject; if (attachments != null) { foreach (var a in attachments) { myMessage.Attachments.Add(new MimeAttachment(a.ContentStream, a.Name)); } } myMessage.IsBodyHtml = true; myMessage.Body = string.Format("<body style=\"font-family: Verdana, arial;font-size:11px\">{0}</body>", body); #if DEBUG myMessage.Body += string.Format("<br> Original recipient: {0} CC: {1} BCC: {2} ", to, cc, bcc); #else if (!string.IsNullOrEmpty(debugMailReceiver)) { myMessage.Body += string.Format("<br> Original recipient: {0} CC: {1} BCC: {2} ", to, cc, bcc); } #endif var mySmtpClient = mailer; if (smtpServer == null) { smtpServer = Properties.Settings.Default.SMTPServer; } if (smtpUserName == null) { smtpUserName = Properties.Settings.Default.SMTPAccount; } if (smtpPassword == null) { smtpPassword = Properties.Settings.Default.SMTPPassword; } if (smtpServer != null) { mySmtpClient.Host = smtpServer; if (smtpServerPortNumber == -1) { mySmtpClient.Port = Properties.Settings.Default.SMTPServerPortNumber; } if (smtpUserName != null) { //NetworkCredential myCredential = new NetworkCredential(smtpUserName,smtpPassword); //mySmtpClient.UseDefaultCredentials = false; //mySmtpClient.Credentials = myCredential; mySmtpClient.User = smtpUserName; mySmtpClient.Password = smtpPassword; mySmtpClient.AuthenticationMode = AuthenticationType.Base64; } //mySmtpClient.ServicePoint.MaxIdleTime = 1; if (Properties.Settings.Default.SMTPSslEnable) { mySmtpClient.SslType = SslMode.Ssl; } } //EventLog.WriteEntry("asaqback",string.Format("Sent message to {0}, cc {1}, bcc {2}, subject {3}",myMessage.To.ToString(),myMessage.CC.ToString(),myMessage.Bcc.ToString(),myMessage.Subject),EventLogEntryType.Information); try { mySmtpClient.SendCompleted += MySmtpClient_SendCompleted; mySmtpClient.SendMailAsync(myMessage); } catch (Exception sException) { string m1 = string.Format("Email is not valid"); string m2 = string.Format("E-mail must be supplied ([email protected])"); string message = string.Format("Error in sending mail to: {0} {1}", to, to.IsEmpty() ? m2:m1); throw new Exception(message, sException); } }