/// <summary> /// This is the main function. All other methods in this class must call it and all emails must be sent trough it. /// </summary> /// <param name="message"></param> /// <param name="client"></param> public virtual void SendMail(MailMessage message, SmtpClientEx client = null, bool forcePreview = false) { if (message == null) { throw new ArgumentNullException(nameof(message)); } var smtp = client ?? SmtpClientEx.Current; // If non-live environment then send preview, except if all recipients are known. var sendPreview = !IsLive && NonErrorRecipientsFound(message); // If not LIVE environment then send preview message to developers instead. MailMessage preview = null; if (forcePreview || sendPreview) { preview = GetMailPreview(message, smtp); } string fileName; // Send preview if available, otherwise send original message. smtp.SendMessage(preview ?? message, out fileName); // Dispose preview message. if (preview != null) { preview.Dispose(); } }
public System.Net.Mail.MailMessage GetMailPreview(MailMessage message) { MailMessage mail = new MailMessage(); mail.IsBodyHtml = true; SmtpClientEx.ApplyRecipients(mail, message.From, Smtp.ErrorRecipients); var subject = message.Subject; ApplyRunModeSuffix(ref subject); mail.Subject = subject; string testBody = ""; testBody += "In LIVE mode this email would be sent:<br />\r\n"; foreach (var item in message.To) { testBody += "To: " + System.Web.HttpUtility.HtmlEncode(item.ToString()) + "<br />\r\n"; } foreach (var item in message.CC) { testBody += "Cc: " + System.Web.HttpUtility.HtmlEncode(item.ToString()) + "<br />\r\n"; } foreach (var item in message.Bcc) { testBody += "Bcc: " + System.Web.HttpUtility.HtmlEncode(item.ToString()) + "<br />\r\n"; } testBody += "<hr />\r\n"; var attachments = message.Attachments; if (attachments != null && attachments.Count() > 0) { testBody += "These files would be attached:<br />\r\n"; if (attachments != null && attachments.Count() > 0) { for (int ctr = 0; ctr <= attachments.Count() - 1; ctr++) { string fileName = attachments[ctr].Name; if (fileName.Length > 3 && fileName.ToLower().Substring(fileName.Length - 4) == ".ics") { mail.Attachments.Add(attachments[ctr]); } testBody += " " + System.Web.HttpUtility.HtmlEncode(fileName); testBody += "<br />\r\n"; } } } if (message.IsBodyHtml) { testBody += message.Body; } else { testBody += "<pre>"; testBody += System.Web.HttpUtility.HtmlEncode(message.Body); testBody += "</pre>"; } mail.Body = testBody; return(mail); }
public EmailAlert(HealthService service, dynamic jsonEmailAlert) { _service = service; _smtpClient = new SmtpClientEx(); _smtpClient.DnsClient = new DnsClientInternal(_service.DnsServer); Reload(jsonEmailAlert); }
public void Send(string email) { SmtpClientEx.QuickSendSmartHost("box.analit.net", 25, Environment.MachineName, "*****@*****.**", new[] { "*****@*****.**" }, File.OpenRead(email)); }
/// <summary> /// Create preview email message from original email message. /// </summary> /// <param name="message">original email message.</param> /// <returns>Preview Message.</returns> public static MailMessage GetMailPreview(MailMessage message, SmtpClientEx client = null) { var smtp = SmtpClientEx.Current; var mail = new MailMessage(); mail.IsBodyHtml = true; Mail.MailHelper.ApplyRecipients(mail, smtp.SmtpFrom, smtp.ErrorRecipients); var subject = message.Subject; ApplyRunModeSuffix(ref subject); mail.Subject = subject; string testBody = ""; testBody += "In LIVE mode this email would be sent:<br /><br />\r\n"; testBody += "<pre>"; testBody += System.Net.WebUtility.HtmlEncode(GetMailHeader(message)); if (client != null) { if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { testBody += string.Format("Delivery Method: {0}\r\n", client.DeliveryMethod); testBody += string.Format("Delivery Folder: {0}\r\n", client.PickupDirectoryLocation); } } testBody += "</pre>"; testBody += "<hr />\r\n"; if (message.IsBodyHtml) { testBody += message.Body; } else { testBody += "<pre>"; testBody += System.Net.WebUtility.HtmlEncode(message.Body); testBody += "</pre>"; } mail.Body = testBody; // Readd attachments. var files = message.Attachments; if (files != null) { for (int i = 0; i < files.Count; i++) { var name = files[i].Name; // Re-attach calendar item. if (name.EndsWith(".ics", StringComparison.OrdinalIgnoreCase)) { mail.Attachments.Add(files[i]); } } } return(mail); }
/// <summary> /// Mail will be sent to error recipient if not LIVE. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="cc"></param> /// <param name="bcc"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="isBodyHtml"></param> /// <param name="preview">Force preview on LIVE system.</param> /// <param name="rethrow">Throw exception if sending fails. Must be set to false when sending exceptions.</param> /// <param name="attachments"></param> public Exception SendMailFrom(string @from, string @to, string cc, string bcc, string subject, string body, bool isBodyHtml, bool preview, bool rethrow, Attachment[] attachments, SmtpDeliveryMethod DeliveryMethod = SmtpDeliveryMethod.Network) { // Re-throw - throw the error again to catch by a caller try { var mail = new MailMessage(); SmtpClientEx.ApplyRecipients(mail, @from, @to, cc, bcc); SmtpClientEx.ApplyAttachments(mail, attachments); mail.IsBodyHtml = isBodyHtml; mail.Subject = subject; mail.Body = body; if (!IsLive || preview) { mail = GetMailPreview(mail); } if (DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { Smtp.SmtpDeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; Smtp.SmtpPickupFolder = SmtpClientEx.Current.SmtpPickupFolder; } Smtp.SendMessage(mail); return(null); } catch (Exception ex) { if (!string.IsNullOrEmpty(@to) && !ex.Data.Contains("Mail.To")) { ex.Data.Add("Mail.To", @to); } if (!string.IsNullOrEmpty(cc) && !ex.Data.Contains("Mail.Cc")) { ex.Data.Add("Mail.Cc", cc); } if (!string.IsNullOrEmpty(bcc) && !ex.Data.Contains("Mail.Bcc")) { ex.Data.Add("Mail.Bcc", bcc); } if (!string.IsNullOrEmpty(subject) && !ex.Data.Contains("Mail.Subject")) { ex.Data.Add("Mail.Subject", subject); } // Will be processed by the caller. if (rethrow) { throw; } else { ProcessException(ex); } return(ex); } }
private void MailWithAttach(ReportExecuteLog log, string address, string[] files, string subjectSufix = null) { var message = new Mime(); var mainEntry = message.MainEntity; mainEntry.From = new AddressList { new MailboxAddress("АналитФармация", "*****@*****.**") }; mainEntry.To = new AddressList(); mainEntry.To.Parse(address); if (!string.IsNullOrEmpty(EMailSubject)) { mainEntry.Subject = EMailSubject; } if (!String.IsNullOrEmpty(subjectSufix)) { if (!String.IsNullOrEmpty(mainEntry.Subject)) { mainEntry.Subject += " "; } mainEntry.Subject += subjectSufix; } mainEntry.ContentType = MediaType_enum.Multipart_mixed; var textEntity = mainEntry.ChildEntities.Add(); textEntity.ContentType = MediaType_enum.Text_plain; textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable; textEntity.DataText = String.Empty; foreach (var file in files) { AttachFile(mainEntry, file); } if (Testing) { Messages.Add(message); } else { var smtpId = SmtpClientEx.QuickSendSmartHostSMTPID(Settings.Default.SMTPHost, null, null, message); ProcessLog(smtpId, message.MainEntity.MessageID, address, log); } }
/// <summary> /// Mail will be sent to error recipient if not LIVE. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="cc"></param> /// <param name="bcc"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="isBodyHtml"></param> /// <param name="preview">Force preview on LIVE system.</param> /// <param name="rethrow">Throw exception if sending fails. Must be set to false when sending exceptions.</param> /// <param name="attachments"></param> public void SendMailFrom(string @from, string @to, string cc, string bcc, string subject, string body, bool isBodyHtml, bool preview, bool rethrow, Attachment[] attachments) { // Re-throw - throw the error again to catch by a caller try { var mail = new MailMessage(); SmtpClientEx.ApplyRecipients(mail, @from, @to, cc, bcc); SmtpClientEx.ApplyAttachments(mail, attachments); mail.IsBodyHtml = isBodyHtml; mail.Subject = subject; mail.Body = body; if (!IsLive || preview) { mail = GetMailPreview(mail); } Smtp.SendMessage(mail); } catch (Exception ex) { if (!string.IsNullOrEmpty(@to) && !ex.Data.Contains("Mail.To")) { ex.Data.Add("Mail.To", @to); } if (!string.IsNullOrEmpty(cc) && !ex.Data.Contains("Mail.Cc")) { ex.Data.Add("Mail.Cc", cc); } if (!string.IsNullOrEmpty(bcc) && !ex.Data.Contains("Mail.Bcc")) { ex.Data.Add("Mail.Bcc", bcc); } if (!string.IsNullOrEmpty(subject) && !ex.Data.Contains("Mail.Subject")) { ex.Data.Add("Mail.Subject", subject); } // Will be processed by the caller. if (rethrow) { throw; } else { ProcessException(ex); } } }
/// <summary> /// This is the main function. All other methods in this class must call it and all emails must be sent trough it. /// </summary> /// <param name="message"></param> /// <param name="client"></param> public virtual void SendMail(MailMessage message, SmtpClientEx client = null, bool forcePreview = false) { var smtp = client ?? SmtpClientEx.Current; // If not LIVE environment then send preview message to developers instead. if (!IsLive || forcePreview) { message = GetMailPreview(message, smtp); } string fileName; smtp.SendMessage(message, out fileName); // Dispose preview message. if (!IsLive || forcePreview) { message.Dispose(); } }
/// <summary> /// This is the main function. All other methods in this class must call it and all emails must be sent trough it. /// </summary> /// <param name="message"></param> /// <param name="client"></param> public virtual void SendMail(MailMessage message, SmtpClientEx client = null, bool forcePreview = false) { var smtp = client ?? SmtpClientEx.Current; // If non-live environment then send preview, except if all recipients are known. var sendPreview = !IsLive && NonErrorRecipientsFound(message); // If not LIVE environment then send preview message to developers instead. if (forcePreview || sendPreview) { message = GetMailPreview(message, smtp); } string fileName; smtp.SendMessage(message, out fileName); // Dispose preview message. if (sendPreview) { message.Dispose(); } }
/// <summary> /// This is the main function. All other methods in this class must call it and all emails must be sent trough it. /// </summary> /// <param name="message"></param> /// <param name="client"></param> public virtual void SendMail(MailMessage message, SmtpClientEx client = null, bool forcePreview = false) { var smtp = client ?? SmtpClientEx.Current; // Send preview if forced preview or non error recipient found. var sendPreview = forcePreview || NonErrorRecipientsFound(message); // If not LIVE environment then send preview message to developers instead. if (sendPreview) { message = GetMailPreview(message, smtp); } string fileName; smtp.SendMessage(message, out fileName); // Dispose preview message. if (sendPreview) { message.Dispose(); } }
public static int Send(MailMessage message) { try { #if DEBUG message.To.Clear(); message.To.Add(GetDebugMail()); message.Bcc.Clear(); message.CC.Clear(); #endif var smtpid = SmtpClientEx.QuickSendSmartHostSMTPID(GetSmtpServer(), "", "", message); if (smtpid == null) { return(0); } return(smtpid.Value); } catch (Exception ex) { _log.Error("Не удалось отправить письмо", ex); } return(0); }
protected virtual void SendUnrecLetter(Mime m, AddressList from, EMailSourceHandlerException exception) { try { var attachments = m.Attachments.Where(a => !String.IsNullOrEmpty(a.GetFilename())).Aggregate("", (s, a) => s + String.Format("\"{0}\"\r\n", a.GetFilename())); var ms = new MemoryStream(m.ToByteData()); #if !DEBUG SmtpClientEx.QuickSendSmartHost( Settings.Default.SMTPHost, 25, Environment.MachineName, Settings.Default.ServiceMail, new[] { Settings.Default.UnrecLetterMail }, ms); #endif FailMailSend(m.MainEntity.Subject, from.ToAddressListString(), m.MainEntity.To.ToAddressListString(), m.MainEntity.Date, ms, attachments, exception.Message); DownloadLogEntity.Log((ulong)PriceSourceType.EMail, String.Format("Письмо не распознано.Причина : {0}; Тема :{1}; От : {2}", exception.Message, m.MainEntity.Subject, from.ToAddressListString())); } catch (Exception exMatch) { _logger.Error("Не удалось отправить нераспознанное письмо", exMatch); } }
public static void Begin(string username, string password, string emailaddress) { // 登录 using (var client = new HttpClient()) { string requestRaw = $@" POST http://oa.zxxk.com/AsynAjax.ashx HTTP/1.1 Host: oa.zxxk.com Connection: keep-alive Content-Length: 87 Pragma: no-cache Cache-Control: no-cache Accept: */* Origin: http://oa.zxxk.com X-Requested-With: XMLHttpRequest User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: http://oa.zxxk.com/Login.html Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.8,en;q=0.6 Type=LoginValidate&UserName={username}&PassWord={password}&LimitDay=0" ; Console.WriteLine(requestRaw); IEnumerable <string> sessionId; var response = client.SendAsync(new HttpRequestMessage().CreateFromRaw(requestRaw)).Result; response.EnsureSuccessStatusCode(); response.Headers.TryGetValues("Set-Cookie", out sessionId); if (sessionId == null) { throw new HttpRequestException("未返回 Set-Cookie, 登录失败"); } var sessionIdList = sessionId as IList <string> ?? sessionId.ToList(); requestRaw = $@"GET http://oa.zxxk.com/Default.aspx HTTP/1.1 Host: oa.zxxk.com Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 Referer: http://oa.zxxk.com/Function/Index.html Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8,en;q=0.6 Cookie: {sessionIdList.FirstOrDefault()}" ; response = client.SendAsync(new HttpRequestMessage().CreateFromRaw(requestRaw)).Result; response.EnsureSuccessStatusCode(); var html = response.Content.ReadAsStringAsync().Result; // 获得待点击URL信息列表 IEnumerable <dynamic> listLi = from m in (null as HtmlNodeNavigator) .Create(html) .SelectSetAsRoot("//li[img]") let title = m.SelectSingle("//@title").Value let url = m.SelectSingle("//@href").Value let date = m.SelectSingle("//span/text()").Value where !Regex.IsMatch(url, "knowledge", RegexOptions.IgnoreCase) select new { Title = title, Url = url, Date = date }; listLi = listLi.ToList(); var taskList = new List <Task <HttpResponseMessage> >(); var listTemp = new Dictionary <int, int>(); // 进行自动点击 var request = new HttpRequestMessage(); foreach (var item in listLi) { request.RequestUri = new Uri(new Uri("http://oa.zxxk.com"), item.Url); var r = client.SendAsync(request.CloneAsync().Result); taskList.Add(r); listTemp[listLi.ToList().IndexOf(item)] = taskList.IndexOf(r); } Task.WhenAll(taskList); string emailStr = taskList.Where(m => !m.IsFaulted && m.Result.IsSuccessStatusCode).Aggregate("", (c, i) => c += listLi.ToList()[listTemp[taskList.IndexOf(i)]].Title + " " + listLi.ToList()[listTemp[taskList.IndexOf(i)]].Date + " " + listLi.ToList()[listTemp[taskList.IndexOf(i)]].Url + " <br/>"); emailStr += $" <br/> 总共 {taskList.Count(m => !m.IsFaulted && m.Result.IsSuccessStatusCode) * 5} 积分到手..."; // 发送邮件 IMessageService emailService = SmtpClientEx.Create("*****@*****.**", "pwuomsefcevacbeg"); emailService.SendMessage(new EmailMessage(emailStr, DateTime.Now + " OA 积分获得情况"), emailaddress); } }
/// <summary> /// Mail will be sent to error recipient if not LIVE. /// </summary> /// <param name="from"></param> /// <param name="to"></param> /// <param name="cc"></param> /// <param name="bcc"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="isBodyHtml"></param> /// <param name="preview">Force preview on LIVE system.</param> /// <param name="rethrow">Throw exception if sending fails. Must be set to false when sending exceptions.</param> /// <param name="attachments"></param> public Exception SendMailFrom(string @from, string @to, string cc, string bcc, string subject, string body, bool isBodyHtml, bool rethrow = false, string[] attachments = null, SmtpDeliveryMethod?overrideDeliveryMethod = null, bool forcePreview = false) { Exception error = null; // Re-throw - throw the error again to catch by a caller var message = new MailMessage(); var smtp = new SmtpClientEx(); try { MailHelper.ApplyRecipients(message, @from, @to, cc, bcc); MailHelper.ApplyAttachments(message, attachments); message.IsBodyHtml = isBodyHtml; message.Subject = subject; message.Body = body; // Override delivery method. if (overrideDeliveryMethod.HasValue) { smtp.DeliveryMethod = overrideDeliveryMethod.Value; } SendMail(message, smtp, forcePreview); } catch (Exception ex) { if (!ex.Data.Contains("Mail.DeliveryMethod")) { ex.Data.Add("Mail.DeliveryMethod", overrideDeliveryMethod); } if (!ex.Data.Contains("Mail.From")) { ex.Data.Add("Mail.From", @from); } if (!string.IsNullOrEmpty(@to) && !ex.Data.Contains("Mail.To")) { ex.Data.Add("Mail.To", @to); } if (!string.IsNullOrEmpty(cc) && !ex.Data.Contains("Mail.Cc")) { ex.Data.Add("Mail.Cc", cc); } if (!string.IsNullOrEmpty(bcc) && !ex.Data.Contains("Mail.Bcc")) { ex.Data.Add("Mail.Bcc", bcc); } if (!string.IsNullOrEmpty(subject) && !ex.Data.Contains("Mail.Subject")) { ex.Data.Add("Mail.Subject", subject); } // Will be processed by the caller. if (rethrow) { throw; } else { Current.ProcessException(ex); } error = ex; } finally { // Attachments and message will be disposed. message.Dispose(); smtp.Dispose(); } return(error); }
/// <summary> /// Create preview email message from original email message. /// </summary> /// <param name="message">original email message.</param> /// <returns>Preview Message.</returns> public static MailMessage GetMailPreview(MailMessage message, SmtpClientEx client = null) { if (message == null) { throw new ArgumentNullException(nameof(message)); } var smtp = SmtpClientEx.Current; var mail = new MailMessage(); mail.IsBodyHtml = true; Mail.MailHelper.ApplyRecipients(mail, smtp.SmtpFrom, smtp.ErrorRecipients); var subject = message.Subject; ApplyRunModeSuffix(ref subject); mail.Subject = subject; string testBody = ""; testBody += "In LIVE mode this email would be sent:<br /><br />\r\n"; testBody += "<pre>"; testBody += string.Format("Source: {0}\r\n", GetSubjectPrefix().Trim(' ', ':')); testBody += System.Net.WebUtility.HtmlEncode(GetMailHeader(message)); if (client != null) { if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { testBody += string.Format("Delivery Method: {0}\r\n", client.DeliveryMethod); testBody += string.Format("Delivery Folder: {0}\r\n", client.PickupDirectoryLocation); } } testBody += "</pre>"; testBody += "<hr />\r\n"; if (message.IsBodyHtml) { testBody += message.Body; } else { testBody += "<pre>"; testBody += System.Net.WebUtility.HtmlEncode(message.Body); testBody += "</pre>"; } mail.Body = testBody; // Read attachments. var files = message.Attachments; if (files != null) { for (int i = 0; i < files.Count; i++) { var name = files[i].Name; // Re-attach calendar item. if (name.EndsWith(".ics", StringComparison.OrdinalIgnoreCase)) { mail.Attachments.Add(files[i]); } } } // Read views var views = message.AlternateViews; if (views != null) { for (int i = 0; i < views.Count; i++) { var view = views[i]; var content = view.ContentType; var name = content.Name; // Re-attach calendar item. if (name.EndsWith(".ics", StringComparison.OrdinalIgnoreCase)) { // Add calendar item as attachment. var attachment = new Attachment(view.ContentStream, name, content.MediaType); mail.Attachments.Add(attachment); //var reader = new System.IO.StreamReader(view.ContentStream); //var calendar = reader.ReadToEnd(); //reader.Dispose(); } } } return(mail); }
public void SendReport(PipelineContext ctx, ImportReport report) { if ((ctx.ImportEngine.ImportFlags & _ImportFlags.NoMailReport) != 0) { return; } if ((Mode & _Mode.Always) != 0) { goto SEND_REPORT; } if ((report.ErrorState & _ErrorState.Error) != 0 && (Mode & _Mode.Errors) != 0) { goto SEND_REPORT; } if ((report.ErrorState & _ErrorState.Limited) != 0 && (Mode & _Mode.Limited) != 0) { goto SEND_REPORT; } return; SEND_REPORT: StringBuilder sb = new StringBuilder(); String fn = ctx.ImportEngine.Xml.FileName; sb.AppendFormat("Import report for {0}.\r\n", fn); if (report.ErrorMessage != null) { sb.AppendFormat("-- LastError={0}\r\n", indentLines(report.ErrorMessage, 6, false)); } sb.AppendFormat("-- Active datasources ({0}):\r\n", report.DatasourceReports.Count); for (int i = 0; i < report.DatasourceReports.Count; i++) { var dsrep = report.DatasourceReports[i]; sb.AppendFormat("-- -- [{0}]: {1} \r\n", dsrep.DatasourceName, indentLines(dsrep.Stats, 9, false)); } String shortName = Path.GetFileName(Path.GetDirectoryName(fn)); ctx.ImportLog.Log("Sending report to {0} (first address)...", MailTo[0]); using (SmtpClientEx smtp = new SmtpClientEx(MailServer, Port)) { using (MailMessage m = new MailMessage()) { m.From = MailFrom; foreach (var x in MailTo) { m.To.Add(x); } m.Subject = String.Format(MailSubject, fn, shortName, report.ErrorState.ToString()); m.SubjectEncoding = Encoding.UTF8; m.BodyEncoding = Encoding.UTF8; m.Body = sb.ToString(); smtp.Send(m); } } ctx.ImportLog.Log("Report is sent successfull."); }
//для того что бы перекрыть в тестах protected virtual void Send(Mime mime) { SmtpClientEx.QuickSendSmartHost(Settings.Default.SMTPHost, 25, String.Empty, mime); }
public void CreateClientTest() { var s = SmtpClientEx.Create("*****@*****.**", "pwuomsefcevacbeg"); s.SendMessage(new EmailMessage($"<h1>Just For Test</h1> ---- {DateTime.Now}"), "*****@*****.**"); }