void ErrorSending(SmtpFailedRecipientsException ex) { foreach (SmtpFailedRecipientException recip in ex.InnerExceptions) { ErrorSending(recip); } }
public void SendToMail(string messageId, string toAddress, string[] param) { XmlDocument xmlDocument = new XmlDocument(); string str = string.Concat(HttpContext.Current.Server.MapPath("\\"), "Mailformat.xml"); string innerText = ""; string innerText1 = ""; int i = 0; if (File.Exists(str)) { xmlDocument.Load(str); XmlNode xmlNodes = xmlDocument.SelectSingleNode(string.Concat("MailFormats/MailFormat[@Id='", messageId, "']")); innerText = xmlNodes.SelectSingleNode("Subject").InnerText; innerText1 = xmlNodes.SelectSingleNode("Body").InnerText; if (param == null) { throw new Exception("Mail format file not found."); } for (i = 0; i <= (int)param.Length - 1; i++) { innerText1 = innerText1.Replace(string.Concat(i.ToString(), "?"), param[i]); innerText = innerText.Replace(string.Concat(i.ToString(), "?"), param[i]); } dynamic mailMessage = new MailMessage(); mailMessage.From = new MailAddress(this.FromAddress); mailMessage.To.Add(toAddress); mailMessage.Subject = innerText; mailMessage.IsBodyHtml = true; mailMessage.Body = innerText1; SmtpClient smtpClient = new SmtpClient() { Host = this.strSmtpClient, EnableSsl = this.EnableSSL, Port = Convert.ToInt32(this.SMTPPort), Credentials = new NetworkCredential(this.UserID, this.Password) }; try { smtpClient.Send(mailMessage); } catch (SmtpFailedRecipientsException smtpFailedRecipientsException1) { SmtpFailedRecipientsException smtpFailedRecipientsException = smtpFailedRecipientsException1; for (int j = 0; j <= (int)smtpFailedRecipientsException.InnerExceptions.Length; j++) { SmtpStatusCode statusCode = smtpFailedRecipientsException.InnerExceptions[j].StatusCode; if (statusCode == SmtpStatusCode.MailboxBusy | statusCode == SmtpStatusCode.MailboxUnavailable) { Thread.Sleep(2000); smtpClient.Send(mailMessage); } } } } }
public void ExtractAllExceptions_Can_extract_innerExceptions_from_SmtpFailedRecipientsException() { // Arrange var ex = new SmtpFailedRecipientsException("failed", new[] { new SmtpFailedRecipientException("Inner 1"), new SmtpFailedRecipientException("Inner 2"), new SmtpFailedRecipientException("Inner 3"), }); // Act var actual = _extractor.ExtractAllExceptions(ex); // Assert actual.Should().HaveCount(4); }
public static IEnumerable <MailMessage> GetMessagesToRetry(MailMessage originalMessage, DateTime originalTimeSent, SmtpFailedRecipientsException exception) { var newBody = GetForwardBody(originalMessage, originalTimeSent); return(exception.InnerExceptions .Select(x => x.FailedRecipient) .Select(failedRecipient => ReSend(failedRecipient, newBody, originalMessage))); }
/// <summary> /// Sends the error report email using the data stored in Session. /// </summary> /// <param name="errorReport">The error report.</param> /// <remarks>Documented by Dev09, 2009-07-16</remarks> private void SendEmail(ErrorReport errorReport) { try { MailMessage mail = new MailMessage(ConfigurationManager.AppSettings["ErrorReportDefaultSender"].ToString(), ConfigurationManager.AppSettings["ErrorReportReceiver"].ToString()); ReportInformation report = new ReportInformation(errorReport.FileName); mail.Subject = string.Format("MemoryLifter Version {0} Error Report", report.MLVersion); // message body containing the user's message and stack trace string separator = ConfigurationManager.AppSettings["EmailSeparator"].ToString(); string reportDate = String.Format("\t\t<p>Report from {0} at {1}</p>\r\n\r\n", report.Date, report.Time); string usermail = String.Format("\t\t<p>User E-Mail:<br />\r\n{0}</p>\r\n\r\n", errorReport.Sender); string message = String.Format("\t\t<p>{0}<br />\r\nUser Message:<br />\r\n{1}<br />\r\n{2}</p>\r\n\r\n", separator, separator, errorReport.Message); string trace = String.Format("\t\t<p>{0}<br />\r\nStack Trace:<br />\r\n{1}<br />\r\n{2}</p>\r\n", separator, separator, errorReport.StackTrace.Replace(Environment.NewLine, "<br />\r\n")); string body = reportDate + usermail + message + trace; mail.Body = "<HTML>\r\n\t<HEAD>\r\n\t\t<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=utf-8'>\r\n\t</HEAD>\r\n\t<BODY>\r\n" + body + "\t</BODY>\r\n</HTML>"; mail.IsBodyHtml = true; mail.BodyEncoding = System.Text.Encoding.UTF8; //include the users mail address as reply-to if (!String.IsNullOrEmpty(errorReport.Sender)) { //OMICRON spam filter kills the mail if the user address is the From-address mail.Headers["Reply-To"] = errorReport.Sender; } // write the attachment to a MemoryStream then attach to email using (MemoryStream ms = new MemoryStream()) { foreach (byte[] dataChunk in errorReport.DataChunks) { ms.Write(dataChunk, 0, dataChunk.Length); } ms.Position = 0; // CRITICAL mail.Attachments.Add(new Attachment(ms, errorReport.FileName, "application/zip")); // send the email through the omicron smtp server SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["MailServer"].ToString()); smtp.Send(mail); } } catch (Exception e) { Log("SendEmail exception: " + e.ToString()); SmtpFailedRecipientsException smtpexp = e as SmtpFailedRecipientsException; if (smtpexp != null) { foreach (SmtpFailedRecipientException recipient in smtpexp.InnerExceptions) { Log("FailedRecipient: " + recipient.FailedRecipient + " StatusCode: " + recipient.StatusCode.ToString()); } } throw; } }
public void Execute(IJobExecutionContext context) { try { string constrj1 = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; SqlConnection mainConnectionj1 = new SqlConnection(constrj1); mainConnectionj1.Open(); string EmailAddress = string.Empty; string Password = string.Empty; string SmtpServer = string.Empty; int Port = 0; SqlConnection conj2 = new SqlConnection(constrj1); conj2.Open(); SqlCommand cmdj2 = new SqlCommand("select * from dbo.AbpSettings", conj2); DataTable dtj2 = new DataTable(); using (SqlDataAdapter sdaj1 = new SqlDataAdapter(cmdj2)) { sdaj1.Fill(dtj2); } foreach (DataRow datarow2 in dtj2.Rows) { if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.Port") { Port = Convert.ToInt32(datarow2["Value"]); } else if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.UserName") { EmailAddress = datarow2["Value"].ToString(); } else if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.Password") { Password = datarow2["Value"].ToString(); } else if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.Host") { SmtpServer = datarow2["Value"].ToString(); } } bool flag = false; string queryj1 = string.Concat("select * from dbo.EmailDetail where IsSent='", flag.ToString(), "' and EmailStatus is null"); DataTable dtj1 = new DataTable(); using (SqlConnection conj1 = new SqlConnection(constrj1)) { using (SqlCommand cmdj1 = new SqlCommand(queryj1)) { cmdj1.Connection = conj1; using (SqlDataAdapter sda = new SqlDataAdapter(cmdj1)) { sda.Fill(dtj1); } } } foreach (DataRow datarow1 in dtj1.Rows) { string From = string.Empty; string To = string.Empty; string Cc = string.Empty; string Subject = string.Empty; string MailBody = string.Empty; if (datarow1["ToEmailAddress"].ToString() != null) { To = datarow1["ToEmailAddress"].ToString(); } if (datarow1["CcEmailAddress"].ToString() != null) { Cc = datarow1["CcEmailAddress"].ToString(); } if (datarow1["Subject"].ToString() != null) { Subject = datarow1["Subject"].ToString(); } if (datarow1["MailBody"].ToString() != null) { MailBody = datarow1["MailBody"].ToString(); } if (Port == 0) { Port = 25; } try { this.WriteToFile("Error 1"); using (MailMessage mm = new MailMessage(EmailAddress, To)) { mm.Subject = Subject; string body = string.Empty; Directory.GetCurrentDirectory(); using (StreamReader reader = new StreamReader("C:\\LockedMail\\TibsNotifyMailTemplate.html")) { body = reader.ReadToEnd(); } body = body.Replace("{Mail_Body}", MailBody); if (!string.IsNullOrEmpty(Cc)) { mm.CC.Add(Cc); } mm.Body = body; mm.IsBodyHtml = true; SmtpClient smtp = new SmtpClient() { Host = SmtpServer, EnableSsl = true }; NetworkCredential credentials = new NetworkCredential() { UserName = EmailAddress, Password = Password }; smtp.UseDefaultCredentials = true; smtp.Credentials = credentials; smtp.Port = Port; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; try { this.WriteToFile("Error 2"); smtp.Send(mm); } catch (SmtpFailedRecipientsException smtpFailedRecipientsException) { SmtpFailedRecipientsException ex = smtpFailedRecipientsException; this.WriteToFile("Catch 1"); for (int i = 0; i < (int)ex.InnerExceptions.Length; i++) { SmtpStatusCode status = ex.InnerExceptions[i].StatusCode; if ((status == SmtpStatusCode.MailboxBusy ? false : status != SmtpStatusCode.MailboxUnavailable)) { this.WriteToFile(string.Concat("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient)); SqlConnection conFinal4 = new SqlConnection(constrj1); conFinal4.Open(); string qurfinal4 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='", ex.InnerExceptions[i].FailedRecipient, "',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " }); (new SqlCommand(qurfinal4, conFinal4)).ExecuteNonQuery(); conFinal4.Close(); } else { this.WriteToFile(string.Concat("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient)); SqlConnection conFinal4 = new SqlConnection(constrj1); conFinal4.Open(); string qurfinal4 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='", ex.InnerExceptions[i].FailedRecipient, "',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " }); (new SqlCommand(qurfinal4, conFinal4)).ExecuteNonQuery(); conFinal4.Close(); } } } catch (Exception exception) { Exception ex = exception; this.WriteToFile(string.Concat("Exception caught in RetryIfBusy(): {0}", ex.ToString())); SqlConnection conFinal3 = new SqlConnection(constrj1); conFinal3.Open(); string qurfinal3 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='", ex.Message, "',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " }); (new SqlCommand(qurfinal3, conFinal3)).ExecuteNonQuery(); conFinal3.Close(); } this.WriteToFile(string.Concat("Email sent successfully to: ", From, " ", To)); SqlConnection conFinal = new SqlConnection(constrj1); conFinal.Open(); string qurfinal = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='Sent',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " }); (new SqlCommand(qurfinal, conFinal)).ExecuteNonQuery(); conFinal.Close(); } } catch (Exception exception1) { Exception ex = exception1; this.WriteToFile("Catch 2"); this.WriteToFile(string.Concat("Error: ", ex.Message)); SqlConnection conFinal2 = new SqlConnection(constrj1); conFinal2.Open(); string qurfinal2 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='Failed',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " }); (new SqlCommand(qurfinal2, conFinal2)).ExecuteNonQuery(); conFinal2.Close(); } } mainConnectionj1.Close(); } catch (Exception exception2) { Exception ex = exception2; this.WriteToFile(string.Concat("Tibs Notify Service Job1 Error on: ", ex.Message, ex.StackTrace)); } }