public void Test7_semicolon_separated_name_addr_containing_quoted_quotes() { string test = "\"test7Meepo; \\\"Meep;\\\" Ratbagger\" <*****@*****.**>; \"Mr. \\\"Oink;\\\" Oinky\" <*****@*****.**>"; string expc = "\"test7Meepo; \\\"Meep;\\\" Ratbagger\" <*****@*****.**>, \"Mr. \\\"Oink;\\\" Oinky\" <*****@*****.**>"; Assert.AreEqual(expc, MailboxAddressListToString(TSmtpSender.ConvertAddressList(test))); }
public void Test3_semicolon_separated_addr_spec() { string test = "[email protected]; [email protected]"; string expected = "[email protected], [email protected]"; Assert.AreEqual(expected, MailboxAddressListToString(TSmtpSender.ConvertAddressList(test))); }
public void Test8_semicolon_separated_name_addr_backslash_quoted_containing_semicolon() { string test = "Meepo\\;Ratbagger <*****@*****.**>; Mr.\\;Oinky <*****@*****.**>"; string expc = "\"Meepo;Ratbagger\" <*****@*****.**>, \"Mr.;Oinky\" <*****@*****.**>"; Assert.AreEqual(expc, MailboxAddressListToString(TSmtpSender.ConvertAddressList(test))); }
/// <summary> /// Gets called in regular intervals from a Timer in Class TTimedProcessing. /// </summary> /// <param name="ADBAccessObj">Instantiated DB Access object with opened DB connection.</param> /// <param name="ARunManually">this is true if the process was called manually from the server admin console</param> public static void Process(TDataBase ADBAccessObj, bool ARunManually) { //At the moment this isn't ready for production use return; #if TODO //TODO: create the gpg files from IntranetExport, with parameters for including finance or personnel string exportpath = TAppSettingsManager.GetValue("OpenPetra.PathExport"); if (Directory.Exists(exportpath) == false) { TLogging.Log("Auto Export directory not found : " + exportpath); return; } //if there is a file there, send it bool foundfile = false; foreach (FileInfo fi in new DirectoryInfo(exportpath).GetFiles("*.gpg")) { foundfile = true; TLogging.Log("Emailing file: " + fi.FullName); //TODO: Get the name of the administrator from the system_defaults table bool result = new TSmtpSender().SendEmail("<*****@*****.**>", "OpenPetra Server", "<*****@*****.**>", "Automatic Intranet Export", "This is an automatic file upload from OpenPetra", new string[] { fi.FullName }); if (result) { TLogging.Log("SMTP Server accepted file: " + fi.FullName); fi.Delete(); //TODO: exception handler } else { TLogging.Log("SMTP Server refused file: " + fi.FullName); } } if (!foundfile) { TLogging.Log("No file found to email"); } #endif }
public void TestSendMail() { if (TAppSettingsManager.GetValue("SmtpHost", TSmtpSender.SMTP_HOST_DEFAULT). EndsWith(TSmtpSender.SMTP_HOST_DEFAULT)) { TLogging.Log("for TestSendMail: need to configure SmptHost in the config file"); return; } TSmtpSender.GetSmtpSettings = @TSmtpSender.GetSmtpSettingsFromAppSettings; TSmtpSender sender = new TSmtpSender(); Assert.AreEqual(true, sender.SendEmail( "*****@*****.**", "OpenPetra Test", "*****@*****.**", "This is a test subject", "Please ignore this e-mail!"), "SendEmail should return true"); }
public void Test3_semicolon_separated_addr_spec() { Assert.AreEqual("[email protected], [email protected]", TSmtpSender.ConvertAddressList("[email protected]; [email protected]")); }
public void Test1_Single_addr_spec() { Assert.AreEqual("*****@*****.**", TSmtpSender.ConvertAddressList("*****@*****.**")); }
public void Test8_semicolon_separated_name_addr_backslash_quoted_containing_semicolon() { Assert.AreEqual("Meepo\\;Ratbagger <*****@*****.**>, Mr.\\;Oinky <*****@*****.**>", TSmtpSender.ConvertAddressList("Meepo\\;Ratbagger <*****@*****.**>; Mr.\\;Oinky <*****@*****.**>")); }
public void Test7_semicolon_separated_name_addr_containing_quoted_quotes() { Assert.AreEqual("\"Meepo; \\\"Meep;\\\" Ratbagger\" <*****@*****.**>, \"Mr. \\\"Oink;\\\" Oinky\" <*****@*****.**>", TSmtpSender.ConvertAddressList("\"Meepo; \\\"Meep;\\\" Ratbagger\" <*****@*****.**>; \"Mr. \\\"Oink;\\\" Oinky\" <*****@*****.**>")); }
/// send an email to the applicant and the registration office public static bool SendEmail(Int64 APartnerKey, string ACountryCode, TApplicationFormData AData, string APDFFilename) { string FileName = TFormLettersTools.GetRoleSpecificFile(TAppSettingsManager.GetValue("Formletters.Path"), "ApplicationReceivedEmail", AData.registrationcountrycode, AData.formsid, "html"); string HTMLText = string.Empty; string SenderAddress = string.Empty; string BCCAddress = string.Empty; string EmailSubject = string.Empty; if (!File.Exists(FileName)) { HTMLText = "<html><body>" + String.Format("Cannot find file {0}", FileName) + "</body></html>"; } else { StreamReader r = new StreamReader(FileName); SenderAddress = r.ReadLine(); BCCAddress = r.ReadLine(); EmailSubject = r.ReadLine(); HTMLText = r.ReadToEnd(); r.Close(); } if (!SenderAddress.StartsWith("From: ")) { throw new Exception("missing From: line in the Email template " + FileName); } if (!BCCAddress.StartsWith("BCC: ")) { throw new Exception("missing BCC: line in the Email template " + FileName); } if (!EmailSubject.StartsWith("Subject: ")) { throw new Exception("missing Subject: line in the Email template " + FileName); } SenderAddress = SenderAddress.Substring("From: ".Length); BCCAddress = BCCAddress.Substring("BCC: ".Length); EmailSubject = EmailSubject.Substring("Subject: ".Length); HTMLText = TJsonTools.ReplaceKeywordsWithData(AData.RawData, HTMLText); HTMLText = HTMLText.Replace("#HTMLRAWDATA", TJsonTools.DataToHTMLTable(AData.RawData)); // load the language file for the specific country Catalog.Init(ACountryCode, ACountryCode); // send email TSmtpSender emailSender = new TSmtpSender(); MailMessage msg = new MailMessage(SenderAddress, AData.email, EmailSubject, HTMLText); msg.Attachments.Add(new Attachment(APDFFilename, System.Net.Mime.MediaTypeNames.Application.Octet)); msg.Bcc.Add(BCCAddress); if (!emailSender.SendMessage(msg)) { TLogging.Log("There has been a problem sending the email to " + AData.email); return(false); } return(true); }
/// <summary> /// Sends a Reminder Email to a Partner. /// </summary> /// <param name="APartnerReminderDR">DataRow containing the Reminder data.</param> /// <param name="AReadWriteTransaction">Already instantiated DB Transaction.</param> /// <param name="Sender">Already instantiated SMTP sender.</param> /// <returns>True if the sending of the Reminder Email succeeded, otherwise false.</returns> private static bool SendReminderEmail(PPartnerReminderRow APartnerReminderDR, TDBTransaction AReadWriteTransaction, TSmtpSender Sender) { string Destination = APartnerReminderDR.EmailAddress; string PartnerShortName; string LanguageCode = "en"; string FirstName = ""; string LastName = ""; if ((Destination == String.Empty) && (APartnerReminderDR.UserId != String.Empty)) { // Get the email and language code of the user GetEmailOfUser(APartnerReminderDR.UserId, AReadWriteTransaction, out Destination, out LanguageCode, out FirstName, out LastName); } // Retrieve ShortName of the Partner about whom the Reminder Email should be sent PartnerShortName = GetPartnerName(APartnerReminderDR.PartnerKey, AReadWriteTransaction); string Domain = TAppSettingsManager.GetValue("Server.Url"); string EMailDomain = TAppSettingsManager.GetValue("Server.EmailDomain"); Dictionary <string, string> emailparameters = new Dictionary <string, string>(); emailparameters.Add("FirstName", FirstName); emailparameters.Add("LastName", LastName); emailparameters.Add("Domain", Domain); emailparameters.Add("partnername", PartnerShortName); emailparameters.Add("partnerkey", string.Format("{0:0000000000}", APartnerReminderDR.PartnerKey)); if (!APartnerReminderDR.IsContactIdNull() && APartnerReminderDR.ContactId != 0) { emailparameters.Add("ContactDetails", GetContactDetails(APartnerReminderDR.ContactId, AReadWriteTransaction)); } if (!APartnerReminderDR.IsReminderReasonNull()) { emailparameters.Add("Reason", APartnerReminderDR.ReminderReason); } if (!APartnerReminderDR.IsEventDateNull()) { emailparameters.Add("EventDate", String.Format("{0}", StringHelper.DateToLocalizedString(APartnerReminderDR.EventDate))); } emailparameters.Add("Comment", APartnerReminderDR.Comment); if (!APartnerReminderDR.IsNextReminderDateNull()) { emailparameters.Add("NextReminderDate", String.Format("{0}", StringHelper.DateToLocalizedString(APartnerReminderDR.NextReminderDate))); } if (APartnerReminderDR.ReminderActive == false) { emailparameters.Add("ReminderDisabled", "true"); } // Send Email (this picks up the SmtpHost AppSetting from the Server Config File) return(Sender.SendEmailFromTemplate( "no-reply@" + EMailDomain, "OpenPetra Admin", Destination, "reminder", LanguageCode, emailparameters)); }
/// <summary> /// Gets called in regular intervals from a Timer in Class TTimedProcessing. /// </summary> /// <param name="ADataBaseObj">Already instatiated DB Access object with opened DB connection.</param> /// <param name="ARunManually">this is true if the process was called manually from the server admin console</param> public static void Process(TDataBase ADataBaseObj, bool ARunManually) { TDBTransaction ReadWriteTransaction; bool NewTransaction; bool LastReminderDateAcquired; DateTime LastReminderDate; DataSet ReminderResultsDS; SSystemDefaultsRow SystemDefaultsDR; PPartnerReminderTable PartnerReminderDT; int ReminderFreqency; TSmtpSender Sender = null; if (TLogging.DebugLevel >= 6) { TLogging.Log("Entering TProcessPartnerReminders.Process..."); } ReadWriteTransaction = ADataBaseObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction); /* * This whole process must either succeed or fail, therefore the whole thing is in a try-catch. */ try { /* * Obtain date when PartnerReminders last ran. This is stored in a SystemDefault. If it doesn't exist already, * a new SystemDefault with an ancient date is created for us. */ LastReminderDateAcquired = GetLastReminderDate(out LastReminderDate, out SystemDefaultsDR, ReadWriteTransaction); if (!LastReminderDateAcquired) { TLogging.Log( TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Could not send Partner Reminders because Petra couldn't create the required SystemDefault setting for the Last Reminder Date!"); ADataBaseObj.RollbackTransaction(); return; } try { Sender = new TSmtpSender(); } catch (ESmtpSenderInitializeException e) { TLogging.Log( TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": " + e.Message); if (e.InnerException != null) { TLogging.Log(e.InnerException.ToString(), TLoggingType.ToLogfile); } return; } // Retrieve all PartnerReminders we need to process. ReminderResultsDS = GetRemindersToProcess(LastReminderDate, out PartnerReminderDT, ADataBaseObj, ReadWriteTransaction); /* * We now have a Typed DataTable with the PartnerReminders that we need to process. * Iterate through the PartnerReminders, update data, and send an email for each PartnerReminder. */ if (TLogging.DebugLevel >= 6) { TLogging.Log("_---------------------------------_"); TLogging.Log("PartnerReminders data before we start processing all PartnerReminders...."); TLogging.Log(ReminderResultsDS.GetXml().ToString()); } foreach (PPartnerReminderRow PartnerReminderDR in PartnerReminderDT.Rows) { if (TLogging.DebugLevel >= 4) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Processing Reminder ID {0} for Partner {1}.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } ReminderFreqency = (PartnerReminderDR.IsReminderFrequencyNull()) ? 0 : PartnerReminderDR.ReminderFrequency; PartnerReminderDR.BeginEdit(); PartnerReminderDR.LastReminderSent = DateTime.Now.Date; PartnerReminderDR.NextReminderDate = DateTime.Now.Date.AddDays(ReminderFreqency); if (!PartnerReminderDR.IsEventDateNull()) // Reminder has an Event Date { if (PartnerReminderDR.NextReminderDate > PartnerReminderDR.EventDate) { if (TLogging.DebugLevel >= 5) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Deactivating Reminder ID {0} for Partner {1} as its Event Date is in the past.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } PartnerReminderDR.ReminderActive = false; } } if (TLogging.DebugLevel >= 4) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Sending email for Reminder ID {0} for Partner {1}.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } Boolean emailSentOk = false; try { emailSentOk = SendReminderEmail(PartnerReminderDR, ReadWriteTransaction, Sender); } catch (ESmtpSenderInitializeException e) // if an exception was thrown, assume the email didn't go. { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Reminder ID {0} for Partner {1}: {2}", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey, e.Message)); if (e.InnerException != null) { TLogging.Log(e.InnerException.Message); } } catch (ESmtpSenderSendException e) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Reminder ID {0} for Partner {1}: {2}", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey, e.Message)); if (e.InnerException != null) { TLogging.Log(e.InnerException.Message); } } catch (Exception e) { TLogging.Log(e.Message); } if (emailSentOk) { // Accept the edit if (TLogging.DebugLevel >= 4) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Reminder ID {0} for Partner {1} accepted by SMTP server.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } PartnerReminderDR.EndEdit(); } else { // Cancel the edit TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Reminder ID {0} for Partner {1} REJECTED by SMTP server.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); PartnerReminderDR.CancelEdit(); } } if (TLogging.DebugLevel >= 6) { TLogging.Log("_---------------------------------_"); TLogging.Log("PartnerReminders data after processing all PartnerReminders, before writing it to DB...."); TLogging.Log(PartnerReminderDT.DataSet.GetXml().ToString()); } // Update all the changed PartnerReminder Rows PPartnerReminderAccess.SubmitChanges(PartnerReminderDT, ReadWriteTransaction); if (TLogging.DebugLevel >= 6) { TLogging.Log("_---------------------------------_"); } /* * Update the SystemDefault that keeps track of when Partner Reminders last ran. * (SystemDefaultsDR will point to the row we loaded earlier on, OR the row we added earlier on * if there wasn't already a SystemDefault row.) */ UpdateLastReminderDate(SystemDefaultsDR, ReadWriteTransaction); if (NewTransaction) { ADataBaseObj.CommitTransaction(); } TLogging.LogAtLevel(1, TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + " ran succesfully."); } catch (Exception Exc) { TLogging.Log( TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + " encountered an Exception:" + Environment.NewLine + Exc.ToString()); if (NewTransaction) { ADataBaseObj.RollbackTransaction(); } throw; } finally { if (Sender != null) { Sender.Dispose(); } } }
/// <summary> /// Takes a report and a list of cost centres; it runs the report for each of the cost centres and emails the results to the address(es) /// associated with that cost centre. Used by Account Detail, Income Expense reports and HOSAs. /// </summary> /// <remarks>If ACostCentreFilter is an SQL clause selecting cost centres, the associated email address is the Primary E-Mail Address of /// every Partner linked to the cost centre. If ACostCentreFilter is "Foreign", the list is every cost centre in the a_email_destination /// table with a File Code of "HOSA".</remarks> /// <param name="FormUtils">The report selection form, to write to the status bar.</param> /// <param name="ReportEngine">FastReport wrapper object.</param> /// <param name="ACalc">The report parameters.</param> /// <param name="ALedgerNumber">The ledger number.</param> /// <param name="ACostCentreFilter">SQL clause to select the list of cost centres to run the report for, or "Foreign" </param> /// <returns>List of status strings that should be shown to the user.</returns> public static List <String> AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine, TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter) { TSmtpSender EmailSender; Int32 SuccessfulCount = 0; var NoEmailAddr = new List <String>(); var FailedAddresses = new List <String>(); var SendReport = new List <String>(); // FastReport will use a temporary folder to store HTML files. // I need to ensure that the CurrectDirectory is somewhere writable: String prevCurrentDir = Directory.GetCurrentDirectory(); //Get a path in the Public Documents folder String newDir = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.CommonDocuments), "OpenPetraOrg"); //Check it exists, and if not create it if (!Directory.Exists(newDir)) { try { Directory.CreateDirectory(newDir); } catch (Exception ex) { //Could not create the path so return useful debugging information: SendReport.Add(Catalog.GetString("Error - could not create directory: ")); SendReport.Add(newDir); SendReport.Add(ex.Message); return(SendReport); } } Directory.SetCurrentDirectory(newDir); // This gets email defaults from the user settings table //TUC_EmailPreferences.LoadEmailDefaults(); try { EmailSender = new TSmtpSender(); EmailSender.SetSender(TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName")); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); } catch (ESmtpSenderInitializeException e) { if (e.InnerException != null) { // I'd write the full exception to the log file, but it still gets transferred to the client window status bar and is _really_ ugly. //TLogging.Log("AutoEmailReports: " + e.InnerException.ToString()); TLogging.Log("AutoEmailReports: " + e.InnerException.Message); } SendReport.Add(e.Message); if (e.ErrorClass == TSmtpErrorClassEnum.secClient) { SendReport.Add(Catalog.GetString("Check the Email tab in User Settings >> Preferences.")); } return(SendReport); } // I need to find the email addresses for the linked partners I'm sending to. DataTable LinkedPartners = null; LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter); LinkedPartners.DefaultView.Sort = "CostCentreCode"; String myLedgerName = ""; DataTable CostCentreList = null; if (ACostCentreFilter == "Foreign") { myLedgerName = TRemote.MFinance.Reporting.WebConnectors.GetLedgerName(ALedgerNumber); CostCentreList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, ALedgerNumber); } foreach (DataRowView rv in LinkedPartners.DefaultView) { DataRow LinkedPartner = rv.Row; Boolean reportAsAttachment = TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment", true); if (LinkedPartner["EmailAddress"].ToString() != "") { ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString()); FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]); MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, reportAsAttachment ? FastReportsWrapper.ReportExportType.Pdf : FastReportsWrapper.ReportExportType.Html); // in OpenSource OpenPetra, we do not have and use the FastReport dlls // if (ReportEngine.FfastReportInstance.ReportInfo.Description == "Empty") // { // continue; // Don't send an empty report // } ReportStream.Position = 0; String EmailBody = ""; if (reportAsAttachment) { EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".pdf"); } else { StreamReader sr = new StreamReader(ReportStream); EmailBody = sr.ReadToEnd(); } String subjectLine; if (ACostCentreFilter == "Foreign") { String recipientLedgerName = ""; CostCentreList.DefaultView.RowFilter = "a_cost_centre_code_c='" + LinkedPartner["CostCentreCode"].ToString() + "'"; if (CostCentreList.DefaultView.Count > 0) { recipientLedgerName = CostCentreList.DefaultView[0].Row["a_cost_centre_name_c"].ToString(); } subjectLine = "HOSA & RGS from " + myLedgerName + " to " + recipientLedgerName; } else { subjectLine = ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]; } Boolean SentOk = EmailSender.SendEmail( LinkedPartner["EmailAddress"].ToString(), subjectLine, EmailBody); if (SentOk) { SuccessfulCount++; } else // Email didn't send for some reason { SendReport.Add(String.Format( Catalog.GetString("Failed to send to {0}. Message returned: \"{1}\"."), LinkedPartner["EmailAddress"], EmailSender.ErrorStatus )); FailedAddresses.Add(" " + LinkedPartner["EmailAddress"]); } } else // No Email Address for this Partner { NoEmailAddr.Add(" " + String.Format("{0:D10}", LinkedPartner["PartnerKey"]) + " " + LinkedPartner["PartnerShortName"]); } } if (SuccessfulCount == 1) { SendReport.Add( String.Format(Catalog.GetString("{0} emailed to {1} partner."), ReportEngine.FReportName, SuccessfulCount)); } else if (SuccessfulCount > 1) { SendReport.Add( String.Format(Catalog.GetString("{0} emailed to {1} partners."), ReportEngine.FReportName, SuccessfulCount)); } else { SendReport.Add(Catalog.GetString( "Error – no cost centre in the report was linked to a Partner with a valid Primary E-mail Address.")); } if (NoEmailAddr.Count > 0) { SendReport.Add(Catalog.GetString("These Partners have no Primary E-mail Address:")); SendReport.AddRange(NoEmailAddr); } if (FailedAddresses.Count > 0) { SendReport.Add(Catalog.GetString("Failed to send email to these addresses:")); SendReport.AddRange(FailedAddresses); } FormUtils.WriteToStatusBar(""); Directory.SetCurrentDirectory(prevCurrentDir); EmailSender.Dispose(); return(SendReport); } // AutoEmailReports
/// <summary> /// Gets called in regular intervals from a Timer in Class TTimedProcessing. /// </summary> /// <param name="ADBAccessObj">Already instatiated DB Access object with opened DB connection.</param> /// <param name="ARunManually">this is true if the process was called manually from the server admin console</param> public static void Process(TDataBase ADBAccessObj, bool ARunManually) { TDBTransaction ReadWriteTransaction; bool NewTransaction; bool LastReminderDateAcquired; DateTime LastReminderDate; DataSet ReminderResultsDS; SSystemDefaultsRow SystemDefaultsDR; PPartnerReminderTable PartnerReminderDT; int ReminderFreqency; TDataBase DBAccessObj; if (TLogging.DebugLevel >= 6) { TLogging.Log("Entering TProcessPartnerReminders.Process..."); } // TODO: it is quite ipossible at the moment to use ADBAccessObj instead of DBAccess.GDBAccessObj due to SubmitChanges etc //DBAccessObj = ADBAccessObj; DBAccessObj = DBAccess.GDBAccessObj; // SubmitChanges references a user TPetraIdentity PetraIdentity = new TPetraIdentity( "SYSADMIN", "", "", "", "", DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, 0, -1, -1, false, false); UserInfo.GUserInfo = new TPetraPrincipal(PetraIdentity, null); ReadWriteTransaction = DBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted, out NewTransaction); /* * This whole process must either succeed or fail, therefore the whole thing is in a try-catch. */ try { /* * Obtain date when PartnerReminders last ran. This is stored in a SystemDefault. If it doesn't exist already, * a new SystemDefault with an ancient date is created for us. */ LastReminderDateAcquired = GetLastReminderDate(out LastReminderDate, out SystemDefaultsDR, ReadWriteTransaction); if (!LastReminderDateAcquired) { TLogging.Log( TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Could not send Partner Reminders because Petra couldn't create the required SystemDefault setting for the Last Reminder Date!"); DBAccessObj.RollbackTransaction(); return; } TSmtpSender Sender = new TSmtpSender(); if (!Sender.FInitOk) { TLogging.Log( TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Could not send Partner Reminders because SMTP server didn't initialise."); DBAccessObj.RollbackTransaction(); return; } // Retrieve all PartnerReminders we need to process. ReminderResultsDS = GetRemindersToProcess(LastReminderDate, out PartnerReminderDT, DBAccessObj, ReadWriteTransaction); /* * We now have a Typed DataTable with the PartnerReminders that we need to process. * Iterate through the PartnerReminders, update data, and send an email for each PartnerReminder. */ if (TLogging.DebugLevel >= 6) { TLogging.Log("_---------------------------------_"); TLogging.Log("PartnerReminders data before we start processing all PartnerReminders...."); TLogging.Log(ReminderResultsDS.GetXml().ToString()); } foreach (PPartnerReminderRow PartnerReminderDR in PartnerReminderDT.Rows) { if (TLogging.DebugLevel >= 4) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Processing Reminder ID {0} for Partner {1}.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } ReminderFreqency = (PartnerReminderDR.IsReminderFrequencyNull()) ? 0 : PartnerReminderDR.ReminderFrequency; PartnerReminderDR.BeginEdit(); PartnerReminderDR.LastReminderSent = DateTime.Now.Date; PartnerReminderDR.NextReminderDate = DateTime.Now.Date.AddDays(ReminderFreqency); if (!PartnerReminderDR.IsEventDateNull()) // Reminder has an Event Date { if (PartnerReminderDR.NextReminderDate > PartnerReminderDR.EventDate) { if (TLogging.DebugLevel >= 5) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Deactivating Reminder ID {0} for Partner {1} as its Event Date is in the past.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } PartnerReminderDR.ReminderActive = false; } } if (TLogging.DebugLevel >= 4) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Sending email for Reminder ID {0} for Partner {1}.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } if (SendReminderEmail(PartnerReminderDR, ReadWriteTransaction, Sender)) { // Accept the edit if (TLogging.DebugLevel >= 4) { TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Reminder ID {0} for Partner {1} accepted by SMTP server.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); } PartnerReminderDR.EndEdit(); } else { // Cancel the edit TLogging.Log(String.Format(TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + ": Reminder ID {0} for Partner {1} REJECTED by SMTP server.", PartnerReminderDR.ReminderId, PartnerReminderDR.PartnerKey)); PartnerReminderDR.CancelEdit(); } } if (TLogging.DebugLevel >= 6) { TLogging.Log("_---------------------------------_"); TLogging.Log("PartnerReminders data after processing all PartnerReminders, before writing it to DB...."); TLogging.Log(PartnerReminderDT.DataSet.GetXml().ToString()); } // Update all the changed PartnerReminder Rows PPartnerReminderAccess.SubmitChanges(PartnerReminderDT, ReadWriteTransaction); if (TLogging.DebugLevel >= 6) { TLogging.Log("_---------------------------------_"); } /* * Update the SystemDefault that keeps track of when Partner Reminders last ran. * (SystemDefaultsDR will point to the row we loaded earlier on, OR the row we added earlier on * if there wasn't already a SystemDefault row.) */ UpdateLastReminderDate(SystemDefaultsDR, ReadWriteTransaction); if (NewTransaction) { DBAccess.GDBAccessObj.CommitTransaction(); } TLogging.LogAtLevel(1, TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + " ran succesfully."); } catch (Exception Exc) { TLogging.Log( TTimedProcessing.StrAutomaticProcessing + StrRemindersProcessing + " encountered an Exception:" + Environment.NewLine + Exc.ToString()); if (NewTransaction) { DBAccess.GDBAccessObj.RollbackTransaction(); } throw; } }
public void Test4_comma_separated_name_addr_quoted() { string test = "\"Meepo Ratbagger\" <*****@*****.**>, \"Mr.Oinky\" <*****@*****.**>"; Assert.AreEqual(test, MailboxAddressListToString(TSmtpSender.ConvertAddressList(test))); }
/// <summary> /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter. /// </summary> /// <returns>Status string that should be shown to the user</returns> public static String AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine, TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter) { Int32 SuccessfulCount = 0; String NoEmailAddr = ""; String FailedAddresses = ""; String SendReport = "Auto Email\r\n"; // // FastReport will use a temporary folder to store HTML files. // I need to ensure that the CurrectDirectory is somewhere writable: String prevCurrentDir = Directory.GetCurrentDirectory(); //Get a path in the Public Documents folder String newDir = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.CommonDocuments), "OpenPetraOrg"); //Check it exists, and if not create it if (!Directory.Exists(newDir)) { try { Directory.CreateDirectory(newDir); } catch (Exception ex) { //could not create the path so return useful debugging information: SendReport += Catalog.GetString("\r\nError - could not create directory: " + newDir); SendReport += Catalog.GetString("\r\n" + newDir); SendReport += ex.Message; return(SendReport); } } Directory.SetCurrentDirectory(newDir); // // I need to find the email addresses for the linked partners I'm sending to. DataTable LinkedPartners = null; LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter); LinkedPartners.DefaultView.Sort = "CostCentreCode"; foreach (DataRowView rv in LinkedPartners.DefaultView) { DataRow LinkedPartner = rv.Row; if (LinkedPartner["EmailAddress"].ToString() != "") { ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString()); FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]); MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html); // in OpenSource OpenPetra, we do not have and use the FastReport dlls // if (ReportEngine.FfastReportInstance.ReportInfo.Description == "Empty") // { // continue; // Don't send an empty report // } ReportStream.Position = 0; // This gets email defaults from the user settings table TUC_EmailPreferences.LoadEmailDefaults(); // This gets some of the settings from the server configuration. We no longer get these items from local PC. // SmtpUsername and SmtpPassword will usually be null string smtpHost, smtpUsername, smtpPassword; int smtpPort; bool smtpUseSSL; TRemote.MSysMan.Application.WebConnectors.GetServerSmtpSettings(out smtpHost, out smtpPort, out smtpUseSSL, out smtpUsername, out smtpPassword); if ((smtpHost == string.Empty) || (smtpPort < 0)) { return(Catalog.GetString( "Cannot send email because 'smtpHost' and/or 'smtpPort' are not configured in the OP server configuration file.")); } TSmtpSender EmailSender = new TSmtpSender(smtpHost, smtpPort, smtpUseSSL, smtpUsername, smtpPassword, ""); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); if (!EmailSender.FInitOk) { return(String.Format( Catalog.GetString( "Failed to set up the email server.\n Please check the settings in Preferences / Email.\n Message returned : \"{0}\""), EmailSender.FErrorStatus)); } String EmailBody = ""; if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment")) { EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".html"); } else { StreamReader sr = new StreamReader(ReportStream); EmailBody = sr.ReadToEnd(); } Boolean SentOk = EmailSender.SendEmail( TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName"), LinkedPartner["EmailAddress"].ToString(), ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"], EmailBody); if (SentOk) { SuccessfulCount++; } else // Email didn't send for some reason { SendReport += String.Format( Catalog.GetString("\r\nFailed to send to {0}. Message returned: \"{1}\"."), LinkedPartner["EmailAddress"], EmailSender.FErrorStatus ); FailedAddresses += ("\r\n " + LinkedPartner["EmailAddress"]); } } else // No Email Address for this Partner { NoEmailAddr += ("\r\n " + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]); } } if (SuccessfulCount > 0) { SendReport += String.Format(Catalog.GetString("\r\n{0} emailed to {1} addresses."), ReportEngine.FReportName, SuccessfulCount) + "\r\n\r\n"; } else { SendReport += Catalog.GetString("\r\nError - no page had a linked email address."); } if (NoEmailAddr != "") { SendReport += (Catalog.GetString("\r\nThese Partners have no email addresses:") + NoEmailAddr + "\r\n"); } if (FailedAddresses != "") { SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n"); } FormUtils.WriteToStatusBar(""); Directory.SetCurrentDirectory(prevCurrentDir); return(SendReport); } // AutoEmailReports
} // Load Hosa Report Data private Boolean LoadStewardshipReportData(TRptCalculator ACalc) { Dictionary <String, TVariant> paramsDictionary = InitialiseDictionary(ACalc); DataTable ReportTable = TRemote.MReporting.WebConnectors.GetReportDataTable("Stewardship", paramsDictionary); if (this.IsDisposed) { return(false); } if (ReportTable == null) { FPetraUtilsObject.WriteToStatusBar("Report Cancelled."); return(false); } MyFastReportsPlugin.RegisterData(ReportTable, "Stewardship"); Boolean HasData = (ReportTable.Rows.Count > 0); if (!HasData) { FStatusMsg += Catalog.GetString("No Stewardship entries found for selected Run Number."); } TParameterList Params = ACalc.GetParameters(); if ((!Params.Get("param_design_template").ToBool()) && (rbtEmailStewardship.Checked)) { // This gets email defaults from the user settings table TUC_EmailPreferences.LoadEmailDefaults(); // This gets some of the settings from the server configuration. We no longer get these items from local PC. // SmtpUsername and SmtpPassword will usually be null string smtpHost, smtpUsername, smtpPassword; int smtpPort; bool smtpUseSSL; TRemote.MSysMan.Application.WebConnectors.GetServerSmtpSettings(out smtpHost, out smtpPort, out smtpUseSSL, out smtpUsername, out smtpPassword); if ((smtpHost == string.Empty) || (smtpPort < 0)) { FStatusMsg += Catalog.GetString( "\r\nCannot send email because 'smtpHost' and/or 'smtpPort' are not configured in the OP server configuration file."); return(false); } TSmtpSender EmailSender = new TSmtpSender(smtpHost, smtpPort, smtpUseSSL, smtpUsername, smtpPassword, ""); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); if (!EmailSender.FInitOk) { FStatusMsg += String.Format( Catalog.GetString( "\r\nFailed to set up the email server.\n Please check the settings in Preferences / Email.\n Message returned: \"{0}\""), EmailSender.FErrorStatus ); return(false); } String MyCostCentreCode = String.Format("{0:##00}00", FLedgerNumber); String PeriodEnd = Params.Get("param_end_date").ToDate().ToString("dd/MM/yyyy"); Int32 RunNumber = Params.Get("param_cmbICHNumber").ToInt32(); String CsvAttachment = String.Format("\"{0}\",{1},\"{2}\",{3},\"{4}\",{5}\n", // "** Header **",30/11/2014,\"0200\",09/12/2014,\"USD\",0" "** Header **", // software originator and version ID PeriodEnd, MyCostCentreCode, // Field Cost Centre Code DateTime.Now.ToString("dd/MM/yyyy"), FLedgerRow.BaseCurrency, // Stewardship Report CSV always in Base Currency RunNumber // Run number ); foreach (DataRow Row in ReportTable.Rows) { CsvAttachment += String.Format("\"{0}\",{1},{2},{3}\n", Row["CostCentreCode"].ToString(), Convert.ToDecimal(Row["Income"]).ToString("0.00", CultureInfo.InvariantCulture), // Stewardship Report CSV always in Base Currency Convert.ToDecimal(Row["Expense"]).ToString("0.00", CultureInfo.InvariantCulture), Convert.ToDecimal(Row["Xfer"]).ToString("0.00", CultureInfo.InvariantCulture) ); } // Andrea wants this systemj default to be manually added to database when we are ready for a system to send ICH emails if (!TSystemDefaults.IsSystemDefaultDefined(STEWARDSHIP_EMAIL_ADDRESS)) { FStatusMsg += Catalog.GetString("\r\n Stewardship email address not configured in System Defaults."); return(false); } String EmailRecipient = TSystemDefaults.GetStringDefault(STEWARDSHIP_EMAIL_ADDRESS); String EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); EmailSender.AttachFromStream(new MemoryStream(Encoding.ASCII.GetBytes(CsvAttachment)), "Stewardship_" + MyCostCentreCode + ".csv"); Boolean SentOk = EmailSender.SendEmail( TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName"), EmailRecipient, //[email protected] "Stewardship Report [" + MyCostCentreCode + "] Period end: " + PeriodEnd + " Run#: " + RunNumber, EmailBody); if (SentOk) { FStatusMsg += Catalog.GetString("\r\nStewardship report emailed to ICH."); } else { FStatusMsg += Catalog.GetString("\r\nFailed to send Stewardship email to ICH."); } return(false); } return(HasData); } // Load Stewardship Report Data
/// <summary> /// Sends a Reminder Email to a Partner. /// </summary> /// <param name="APartnerReminderDR">DataRow containing the Reminder data.</param> /// <param name="AReadWriteTransaction">Already instantiated DB Transaction.</param> /// <param name="Sender">Already instantiated SMTP sender.</param> /// <returns>True if the sending of the Reminder Email succeeded, otherwise false.</returns> private static bool SendReminderEmail(PPartnerReminderRow APartnerReminderDR, TDBTransaction AReadWriteTransaction, TSmtpSender Sender) { string Subject = ""; string Body = ""; string Destination = APartnerReminderDR.EmailAddress; string PartnerShortName; char LF = Convert.ToChar(10); // Retrieve ShortName of the Partner to which the Reminder Email should be sent PartnerShortName = GetPartnerShortName(APartnerReminderDR.PartnerKey); // Format Email Recipient Address as per email RFC's if (!Destination.Trim().StartsWith("<")) { Destination = "<" + Destination; } if (!Destination.Trim().EndsWith(">")) { Destination = Destination + ">"; } // Compose Email Subject Subject = String.Format("OpenPetra Reminder about {0}", PartnerShortName); /* * Compose Email Body */ Body = string.Format("Partner: {0} [{1:0000000000}]{2}", PartnerShortName, APartnerReminderDR.PartnerKey, LF); if (APartnerReminderDR.ContactId != 0) { Body += GetContactDetails(APartnerReminderDR.ContactId, AReadWriteTransaction); } Body += String.Format("Reason: {0}{1}", APartnerReminderDR.ReminderReason, LF); if (!APartnerReminderDR.IsEventDateNull()) { Body += String.Format("Event Date: {0}{1}", StringHelper.DateToLocalizedString(APartnerReminderDR.EventDate), LF); } Body += String.Format("Comment: {0}{1}", APartnerReminderDR.Comment, LF); Body += String.Format("{0}Next Reminder: {1}{2}", LF, StringHelper.DateToLocalizedString(APartnerReminderDR.NextReminderDate), LF); if (APartnerReminderDR.ReminderActive == false) { Body += String.Format("This Reminder has now been disabled.{0}", LF); } // Send Email (this picks up the SMTPServer AppSetting from the Server Config File) return(Sender.SendEmail(Destination, "OpenPetra Server", Destination, Subject, Body)); }
public void Test5_semicolon_separated_name_addr_quoted() { Assert.AreEqual("\"Meepo Ratbagger\" <*****@*****.**>, \"Mr. Oinky\" <*****@*****.**>", TSmtpSender.ConvertAddressList("\"Meepo Ratbagger\" <*****@*****.**>; \"Mr. Oinky\" <*****@*****.**>")); }
/// <summary> /// send report as email /// </summary> public Boolean SendEmail(string AEmailAddresses, bool AAttachExcelFile, bool AAttachCSVFile, bool AAttachPDF, bool AWrapColumn, out TVerificationResultCollection AVerification) { TSmtpSender EmailSender = null; string EmailBody = ""; AVerification = new TVerificationResultCollection(); try { EmailSender = new TSmtpSender(); List <string> FilesToAttach = new List <string>(); if (AAttachExcelFile) { string ExcelFile = TFileHelper.GetTempFileName( FParameterList.Get("currentReport").ToString(), ".xlsx"); if (ExportToExcelFile(ExcelFile)) { FilesToAttach.Add(ExcelFile); } } if (AAttachCSVFile) { string CSVFile = TFileHelper.GetTempFileName( FParameterList.Get("currentReport").ToString(), ".csv"); if (ExportToCSVFile(CSVFile)) { FilesToAttach.Add(CSVFile); } } if (AAttachPDF) { string PDFFile = TFileHelper.GetTempFileName( FParameterList.Get("currentReport").ToString(), ".pdf"); if (PrintToPDF(PDFFile, AWrapColumn)) { FilesToAttach.Add(PDFFile); } } if (FilesToAttach.Count == 0) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), Catalog.GetString("Missing any attachments, not sending the email"), "Missing Attachments", TResultSeverity.Resv_Critical, new System.Guid())); return(false); } try { EmailSender.SetSender(TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName")); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); } catch (ESmtpSenderInitializeException e) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), String.Format("{0}\n{1}", e.Message, Catalog.GetString("Check the Email tab in User Settings >> Preferences.")), CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION, TResultSeverity.Resv_Critical, new System.Guid())); if (e.InnerException != null) { TLogging.Log("Email XML Report: " + e.InnerException); } return(false); } if (EmailBody == "") { EmailBody = Catalog.GetString("OpenPetra report attached."); } if (EmailSender.SendEmail( AEmailAddresses, FParameterList.Get("currentReport").ToString(), EmailBody, FilesToAttach.ToArray())) { foreach (string file in FilesToAttach) { File.Delete(file); } return(true); } AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), Catalog.GetString("Problem sending email"), "Server problems", TResultSeverity.Resv_Critical, new System.Guid())); return(false); } // try catch (ESmtpSenderInitializeException e) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), e.Message, CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION, TResultSeverity.Resv_Critical, new System.Guid())); if (e.InnerException != null) { TLogging.Log("Email XML Report: " + e.InnerException); } return(false); } finally { if (EmailSender != null) { EmailSender.Dispose(); } } }
/// <summary> /// Sends a Reminder Email to a Partner. /// </summary> /// <param name="APartnerReminderDR">DataRow containing the Reminder data.</param> /// <param name="AReadWriteTransaction">Already instantiated DB Transaction.</param> /// <param name="Sender">Already instantiated SMTP sender.</param> /// <returns>True if the sending of the Reminder Email succeeded, otherwise false.</returns> private static bool SendReminderEmail(PPartnerReminderRow APartnerReminderDR, TDBTransaction AReadWriteTransaction, TSmtpSender Sender) { string Subject = ""; string Body = ""; string Destination = APartnerReminderDR.EmailAddress; string PartnerShortName; char LF = Convert.ToChar(10); // Retrieve ShortName of the Partner about whom the Reminder Email should be sent PartnerShortName = GetPartnerShortName(APartnerReminderDR.PartnerKey, AReadWriteTransaction); // Compose Email Subject Subject = String.Format("OpenPetra Reminder about {0}", PartnerShortName); /* * Compose Email Body */ Body = string.Format("Partner: {0} [{1:0000000000}]{2}", PartnerShortName, APartnerReminderDR.PartnerKey, LF); if (APartnerReminderDR.ContactId != 0) { Body += GetContactDetails(APartnerReminderDR.ContactId, AReadWriteTransaction); } Body += String.Format("Reason: {0}{1}", APartnerReminderDR.ReminderReason, LF); if (!APartnerReminderDR.IsEventDateNull()) { Body += String.Format("Event Date: {0}{1}", StringHelper.DateToLocalizedString(APartnerReminderDR.EventDate), LF); } Body += String.Format("Comment: {0}{1}", APartnerReminderDR.Comment, LF); Body += String.Format("{0}Next Reminder: {1}{2}", LF, StringHelper.DateToLocalizedString(APartnerReminderDR.NextReminderDate), LF); if (APartnerReminderDR.ReminderActive == false) { Body += String.Format("This Reminder has now been disabled.{0}", LF); } // Send Email (this picks up the SmtpHost AppSetting from the Server Config File) return(Sender.SendEmail(TAppSettingsManager.GetValue("NoReplyEmailAddress", "*****@*****.**"), "OpenPetra Server", Destination, Subject, Body)); }
public static String ExportToIntranet(Boolean AExportDonationData, Boolean AExportFieldData, Boolean AExportPersonData, String AServerEmailAddress, String APswd, Int32 ADaySpan, String AOptionalMetadata, String ReplyToEmail) { try { FZipFileNames.Clear(); FExportFilePath = TAppSettingsManager.GetValue("OpenPetra.PathTemp") + @"\"; FExportTrace = "Exporting (Temporary path: " + FExportFilePath + ")\r\n"; FTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted); if (AExportDonationData) { ExportDonations(ADaySpan); AddZipFile("donor.csv"); AddZipFile("donation.csv"); AddZipFile("recipient.csv"); } if (AExportFieldData) { if (ExportField()) { AddZipFile("field.csv"); } } if (AExportPersonData) { ExportPersonnel(); AddZipFile("position.csv"); AddZipFile("person.csv"); AddZipFile("email.csv"); } ExportMetadata(AOptionalMetadata, APswd); AddZipFile("metadata.csv"); MemoryStream ZippedStream = TFileHelper.Streams.Compression.DeflateFilesIntoMemoryStream(FZipFileNames.ToArray(), false, ""); TFileHelper.Streams.FileHandling.SaveStreamToFile(ZippedStream, FExportFilePath + "data.zip"); FExportTrace += "\r\nFiles compressed to " + FExportFilePath + "data.zip."; if (EncryptUsingPublicKey("data.zip", AServerEmailAddress)) { TSmtpSender SendMail = new TSmtpSender( TUserDefaults.GetStringDefault("SmtpHost"), TUserDefaults.GetInt16Default("SmtpPort"), TUserDefaults.GetBooleanDefault("SmtpUseSsl"), TUserDefaults.GetStringDefault("SmtpUser"), TUserDefaults.GetStringDefault("SmtpPassword"), ""); String SenderAddress = ReplyToEmail; MailMessage msg = new MailMessage(SenderAddress, AServerEmailAddress, "Data from OpenPetra", "Here is the latest data from my field."); msg.Attachments.Add(new Attachment(FExportFilePath + "data.zip.gpg")); if (SendMail.SendMessage(msg)) { FExportTrace += ("\r\nEmail sent to " + msg.To[0].Address); } else { FExportTrace += ("\r\nNo Email was sent."); } msg.Dispose(); // If I don't call this, the attached files are still locked! } else { FExportTrace += "\r\nError: Data encryption failed."; } } catch (Exception e) { FExportTrace += ("\r\nException: " + e.Message); } finally { DBAccess.GDBAccessObj.RollbackTransaction(); DeleteTemporaryFiles(); DonorList.Clear(); RecipientList.Clear(); // These lists are static so they'll stick around for ever, // but I don't need to keep the data which is taking up memory. } return(FExportTrace); }
/// <summary> /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter. /// </summary> /// <param name="ACalc"></param> /// <param name="ALedgerNumber"></param> /// <param name="ACostCentreFilter"></param> public void AutoEmailReports(TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter) { Int32 SuccessfulCount = 0; String NoEmailAddr = ""; String FailedAddresses = ""; // // I need to find the email addresses for the linked partners I'm sending to. DataTable LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter); LinkedPartners.DefaultView.Sort = "CostCentreCode"; foreach (DataRowView rv in LinkedPartners.DefaultView) { DataRow LinkedPartner = rv.Row; if (LinkedPartner["EmailAddress"].ToString() != "") { ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString()); FPetraUtilsObject.WriteToStatusBar("Generate " + FReportName + " Report for " + LinkedPartner["PartnerShortName"]); MemoryStream ReportStream = FPetraUtilsObject.FFastReportsPlugin.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html); ReportStream.Position = 0; TUC_EmailPreferences.LoadEmailDefaults(); TSmtpSender EmailSender; try { EmailSender = new TSmtpSender( TUserDefaults.GetStringDefault("SmtpHost"), TUserDefaults.GetInt16Default("SmtpPort"), TUserDefaults.GetBooleanDefault("SmtpUseSsl"), TUserDefaults.GetStringDefault("SmtpUser"), TUserDefaults.GetStringDefault("SmtpPassword"), ""); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); } catch (Exception) { MessageBox.Show(Catalog.GetString( "Failed to set up the email server.\nPlease check the settings in Preferences / Email."), Catalog.GetString("Auto-email to linked partners")); return; } String EmailBody = ""; if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment")) { EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); EmailSender.AttachFromStream(ReportStream, FReportName + ".html"); } else { StreamReader sr = new StreamReader(ReportStream); EmailBody = sr.ReadToEnd(); } Boolean SentOk = EmailSender.SendEmail( TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName"), "*****@*****.**", //LinkedPartner["EmailAddress"] FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"], EmailBody); if (SentOk) { SuccessfulCount++; } else // Email didn't send for some reason { FailedAddresses += ("\r\n" + LinkedPartner["EmailAddress"]); } } else // No Email Address for this Partner { NoEmailAddr += ("\r\n" + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]); } } String SendReport = ""; if (SuccessfulCount > 0) { SendReport += String.Format(Catalog.GetString("Reports emailed to {0} addresses."), SuccessfulCount) + "\r\n\r\n"; } if (NoEmailAddr != "") { SendReport += (Catalog.GetString("These Partners have no email addresses:") + NoEmailAddr + "\r\n\r\n"); } if (FailedAddresses != "") { SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n"); } MessageBox.Show(SendReport, Catalog.GetString("Auto-email to linked partners")); FPetraUtilsObject.WriteToStatusBar(""); } // AutoEmailReports
/// <summary> /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter. /// </summary> /// <returns>Status string that should be shown to the user</returns> public static String AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine, TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter) { Int32 SuccessfulCount = 0; String NoEmailAddr = ""; String FailedAddresses = ""; String SendReport = ""; // // I need to find the email addresses for the linked partners I'm sending to. DataTable LinkedPartners = null; LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter); LinkedPartners.DefaultView.Sort = "CostCentreCode"; foreach (DataRowView rv in LinkedPartners.DefaultView) { DataRow LinkedPartner = rv.Row; if (LinkedPartner["EmailAddress"].ToString() != "") { ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString()); FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]); MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html); if (ReportStream.Position < 1000) { continue; // Don't send an empty report } ReportStream.Position = 0; TUC_EmailPreferences.LoadEmailDefaults(); TSmtpSender EmailSender = new TSmtpSender( TUserDefaults.GetStringDefault("SmtpHost"), TUserDefaults.GetInt16Default("SmtpPort"), TUserDefaults.GetBooleanDefault("SmtpUseSsl"), TUserDefaults.GetStringDefault("SmtpUser"), TUserDefaults.GetStringDefault("SmtpPassword"), ""); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); if (!EmailSender.FInitOk) { return(String.Format( Catalog.GetString( "Failed to set up the email server.\n Please check the settings in Preferences / Email.\n Message returned : \"{0}\""), EmailSender.FErrorStatus)); } String EmailBody = ""; if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment")) { EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".html"); } else { StreamReader sr = new StreamReader(ReportStream); EmailBody = sr.ReadToEnd(); } Boolean SentOk = EmailSender.SendEmail( TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName"), "*****@*****.**", //LinkedPartner["EmailAddress"] ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"], EmailBody); if (SentOk) { SuccessfulCount++; } else // Email didn't send for some reason { SendReport += String.Format( Catalog.GetString("\r\nFailed to send to {0}. Message returned: \"{1}\"."), LinkedPartner["EmailAddress"], EmailSender.FErrorStatus ); FailedAddresses += ("\r\n " + LinkedPartner["EmailAddress"]); } } else // No Email Address for this Partner { NoEmailAddr += ("\r\n " + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]); } } if (SuccessfulCount > 0) { SendReport += String.Format(Catalog.GetString("\r\n{0} emailed to {1} addresses."), ReportEngine.FReportName, SuccessfulCount) + "\r\n\r\n"; } if (NoEmailAddr != "") { SendReport += (Catalog.GetString("\r\nThese Partners have no email addresses:") + NoEmailAddr + "\r\n"); } if (FailedAddresses != "") { SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n"); } FormUtils.WriteToStatusBar(""); return(SendReport); } // AutoEmailReports
/// <summary> /// send report as email /// </summary> public Boolean SendEmail(string AEmailAddresses, bool AAttachExcelFile, bool AAttachCSVFile, bool AAttachPDF, bool AWrapColumn, out TVerificationResultCollection AVerification) { TSmtpSender EmailSender = new TSmtpSender(); AVerification = new TVerificationResultCollection(); if (!EmailSender.ValidateEmailConfiguration()) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), Catalog.GetString("Missing configuration for sending emails. Please edit your server configuration file"), CommonErrorCodes.ERR_MISSINGEMAILCONFIGURATION, TResultSeverity.Resv_Critical, new System.Guid())); return(false); } List <string> FilesToAttach = new List <string>(); if (AAttachExcelFile) { string ExcelFile = TFileHelper.GetTempFileName( FParameterList.Get("currentReport").ToString(), ".xlsx"); if (ExportToExcelFile(ExcelFile)) { FilesToAttach.Add(ExcelFile); } } if (AAttachCSVFile) { string CSVFile = TFileHelper.GetTempFileName( FParameterList.Get("currentReport").ToString(), ".csv"); if (ExportToCSVFile(CSVFile)) { FilesToAttach.Add(CSVFile); } } if (AAttachPDF) { string PDFFile = TFileHelper.GetTempFileName( FParameterList.Get("currentReport").ToString(), ".pdf"); if (PrintToPDF(PDFFile, AWrapColumn)) { FilesToAttach.Add(PDFFile); } } if (FilesToAttach.Count == 0) { AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), Catalog.GetString("Missing any attachments, not sending the email"), "Missing Attachments", TResultSeverity.Resv_Critical, new System.Guid())); return(false); } // TODO use the email address of the user, from s_user if (EmailSender.SendEmail("<" + TAppSettingsManager.GetValue("Reports.Email.Sender") + ">", "OpenPetra Reports", AEmailAddresses, FParameterList.Get("currentReport").ToString(), Catalog.GetString("Please see attachment!"), FilesToAttach.ToArray())) { foreach (string file in FilesToAttach) { File.Delete(file); } return(true); } AVerification.Add(new TVerificationResult( Catalog.GetString("Sending Email"), Catalog.GetString("Problem sending email"), "server problems", TResultSeverity.Resv_Critical, new System.Guid())); return(false); }
public void Test1_Single_addr_spec() { string test = "*****@*****.**"; Assert.AreEqual(test, MailboxAddressListToString(TSmtpSender.ConvertAddressList(test))); }
public void Test2_comma_separated_addr_spec() { string test = "[email protected], [email protected]"; Assert.AreEqual(test, MailboxAddressListToString(TSmtpSender.ConvertAddressList(test))); }
} // Load Hosa Report Data private Boolean LoadStewardshipReportData(TRptCalculator ACalc) { Dictionary <String, TVariant> paramsDictionary = InitialiseDictionary(ACalc); DataTable ReportTable = TRemote.MReporting.WebConnectors.GetReportDataTable("Stewardship", paramsDictionary); if (this.IsDisposed) { return(false); } if (ReportTable == null) { FPetraUtilsObject.WriteToStatusBar("Report Cancelled."); return(false); } MyFastReportsPlugin.RegisterData(ReportTable, "Stewardship"); Boolean HasData = (ReportTable.Rows.Count > 0); if (!HasData) { FStatusMsg += Catalog.GetString("No Stewardship entries found for selected Run Number."); } TParameterList Params = ACalc.GetParameters(); if ((!Params.Get("param_design_template").ToBool()) && (rbtEmailStewardship.Checked)) { TUC_EmailPreferences.LoadEmailDefaults(); TSmtpSender EmailSender = new TSmtpSender( TUserDefaults.GetStringDefault("SmtpHost"), TUserDefaults.GetInt16Default("SmtpPort"), TUserDefaults.GetBooleanDefault("SmtpUseSsl"), TUserDefaults.GetStringDefault("SmtpUser"), TUserDefaults.GetStringDefault("SmtpPassword"), ""); EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo"); EmailSender.ReplyTo = TUserDefaults.GetStringDefault("SmtpReplyTo"); if (!EmailSender.FInitOk) { FStatusMsg += String.Format( Catalog.GetString( "\r\nFailed to set up the email server.\n Please check the settings in Preferences / Email.\n Message returned: \"{0}\""), EmailSender.FErrorStatus ); return(false); } String MyCostCentreCode = String.Format("{0:##00}00", FLedgerNumber); String PeriodEnd = Params.Get("param_end_date").ToDate().ToString("dd/MM/yyyy"); Int32 RunNumber = Params.Get("param_cmbICHNumber").ToInt32(); String CsvAttachment = String.Format("\"{0}\",{1},\"{2}\",{3},\"{4}\",{5}\n", // "OP:1",30/11/2014,\"0200\",09/12/2014,\"USD\",0" "OP:1", // software originator and version ID PeriodEnd, MyCostCentreCode, // Field Cost Centre Code DateTime.Now.ToString("dd/MM/yyyy"), FLedgerRow.BaseCurrency, // Stewardship Report CSV always in Base Currency RunNumber // Run number ); foreach (DataRow Row in ReportTable.Rows) { CsvAttachment += String.Format("\"{0}\",{1},{2},{3}\n", Row["CostCentreCode"].ToString(), Convert.ToDecimal(Row["Income"]).ToString("0.00", CultureInfo.InvariantCulture), // Stewardship Report CSV always in Base Currency Convert.ToDecimal(Row["Expense"]).ToString("0.00", CultureInfo.InvariantCulture), Convert.ToDecimal(Row["Xfer"]).ToString("0.00", CultureInfo.InvariantCulture) ); } String EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody"); EmailSender.AttachFromStream(new MemoryStream(Encoding.ASCII.GetBytes(CsvAttachment)), "Stewardship_" + MyCostCentreCode + ".csv"); Boolean SentOk = EmailSender.SendEmail( TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName"), "*****@*****.**", //[email protected] "Stewardship Report [" + MyCostCentreCode + "] Period end: " + PeriodEnd + " Run#: " + RunNumber, EmailBody); if (SentOk) { FStatusMsg += Catalog.GetString("\r\nStewardship report emailed to ICH."); } else { FStatusMsg += Catalog.GetString("\r\nFailed to send Stewardship email to ICH."); } return(false); } return(HasData); } // Load Stewardship Report Data