/// <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)); }
/// <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 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"); }
/// <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> /// 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); }
/// <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> /// 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 = "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> /// 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
} // 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