protected void Page_Load(object sender, EventArgs e) { settingsMasterPage = (SettingsMasterPage)Page.Master; settingsMasterPage.InitializeMasterPageComponents(); int smtpServerId; Boolean isNumeric = int.TryParse(Request.QueryString["smtpServerId"], out smtpServerId); if (!isNumeric) { EmbedClientScript.ShowErrorMessage(this, "Os parâmetros passados para a página não estão em um formato válido.", true); return; } Tenant tenant = (Tenant)Session["tenant"]; smtpServerDAO = new SmtpServerDAO(settingsMasterPage.dataAccess.GetConnection()); SmtpServer smtpServer = smtpServerDAO.GetSmtpServer(tenant.id, smtpServerId); if (smtpServer == null) { smtpServer = new SmtpServer(); smtpServer.tenantId = tenant.id; } SettingsInput settingsInput = new SettingsInput(settingsArea, null); settingsInput.AddHidden("txtId", smtpServer.id.ToString()); settingsInput.AddHidden("txtTenantId", smtpServer.tenantId.ToString()); settingsInput.Add("txtName", "Nome", smtpServer.name); settingsInput.Add("txtAddress", "Endereço", smtpServer.address); settingsInput.Add("txtPort", "Porta", smtpServer.port.ToString()); settingsInput.Add("txtUsername", "Usuário", smtpServer.username); settingsInput.Add("txtPassword", "Senha", smtpServer.password, true, null); }
private void ProcessMailing(MailingDAO mailingDAO, Mailing mailing) { SmtpServerDAO smtpServerDAO = new SmtpServerDAO(dataAccess.GetConnection()); SmtpServer smtpServer = smtpServerDAO.GetSmtpServer(currentTenant, mailing.smtpServer); ReportFrequencyEnum reportFrequency = (ReportFrequencyEnum)mailing.frequency; ReportTypeEnum reportType = (ReportTypeEnum)mailing.reportType; String recipients = mailing.recipients; DateTime lastSend = mailing.lastSend; // Verifica se está na data de envio, aborta caso não esteja if (!ReportContext.IsScheduledTime(reportFrequency, currentPeriodEndDate)) { return; } // Verifica se o log foi importado PrintLogPersistence logPersistence = new PrintLogPersistence(currentTenant, dataAccess.GetConnection(), null, false); Boolean logImported = logPersistence.FileImported(ReportContext.GetDateRange(reportFrequency)); // Verifica se o relatório já foi enviado hoje Boolean alreadySent = lastSend.Date == DateTime.Now.Date; // Caso o log tenha sido importado e se ainda não enviou, gera o relatório e envia if ((logImported) && (!alreadySent)) { // Inicia o append no arquivo de log (acrescentando o "startingDelimiter") fileLogger.LogInfo("Envio de relatório - Iniciando execução...", true); // Informa dados do mailing fileLogger.LogInfo("Frequência de envio - reportFrequency = " + reportFrequency.ToString()); fileLogger.LogInfo("Relatório - reportType = " + reportType.ToString()); fileLogger.LogInfo("Destinatários - recipients = " + recipients); notifications.Clear(); String reportStamp = DateTime.Now.Ticks.ToString(); String reportFilename = FileResource.MapDesktopResource("Report" + reportStamp + currentFormatExtension); BuildReport(reportFilename, reportType, reportFrequency); String mailSubject = "Relatório " + ReportContext.GetFrequencyCaption(reportFrequency); List <String> attachmentFiles = new List <String>(); attachmentFiles.Add(reportFilename); MailSender mailSender = new MailSender(smtpServer.CreateSysObject(), this); mailSender.SetContents("Email gerado automaticamente, não responder.", attachmentFiles); Boolean success = mailSender.SendMail(mailSubject, currentSysSender, recipients); ProcessNotifications(); if (success) // Grava a data de envio de envio no banco { mailing.lastSend = DateTime.Now.Date; mailingDAO.SetMailing(mailing); fileLogger.LogInfo("Execução concluída."); } } // Tenta remover arquivos temporários, ignora caso os arquivos estejam em uso // tentará novamente nas próximas execuções ReportContext.TryRemoveTempFiles(); }
private void SetTenantDefaultSmtp() { SmtpServer server = new SmtpServer(); server.tenantId = tenant.id; server.name = "Servidor Default"; server.address = "smtp.gmail.com"; server.port = 587; server.username = "******"; server.password = "******"; server.hash = Cipher.GenerateHash(tenant.name + server.name); SmtpServerDAO smtpServerDAO = new SmtpServerDAO(sqlConnection); smtpServerDAO.SetSmtpServer(server); }
protected void Page_Load(object sender, EventArgs e) { accountingMasterPage = (AccountingMasterPage)Page.Master; accountingMasterPage.InitializeMasterPageComponents(); dataAccess = accountingMasterPage.dataAccess; if (!Authorization.AuthorizedAsAdministrator(Session)) { // Mostra aviso de falta de autorização ShowWarning(Authorization.GetWarning()); return; } int smtpServerId; Boolean paramExists = !String.IsNullOrEmpty(Request.QueryString["smtpServerId"]); Boolean isNumeric = int.TryParse(Request.QueryString["smtpServerId"], out smtpServerId); if ((paramExists) && (!isNumeric)) { // Mostra aviso de inconsistência nos parâmetros ShowWarning(ArgumentBuilder.GetWarning()); return; } smtpServerDAO = new SmtpServerDAO(dataAccess.GetConnection()); if (paramExists) // Se o parametro existe é uma exclusão { smtpServerDAO.RemoveSmtpServer(smtpServerId); Response.Redirect("ConfigSmtpServers.aspx"); // Limpa a QueryString para evitar erros } Tenant tenant = (Tenant)Session["tenant"]; List <Object> serverList = smtpServerDAO.GetAllSmtpServers(tenant.id); int defaultItemId = 0; if (serverList.Count > 0) { // Considera como sendo item default o primeiro smtp server criado para o tenant SmtpServer defaultItem = (SmtpServer)serverList[0]; defaultItemId = defaultItem.id; } String[] columnNames = new String[] { "Nome Servidor", "Endereço", "Porta" }; String alterScript = "window.open('SmtpServerSettings.aspx?smtpServerId=' + {0}, 'Settings', 'width=540,height=600');"; String removeScript = "var confirmed = confirm('Deseja realmente excluir este item?'); if (confirmed) window.location='ConfigSmtpServers.aspx?smtpServerId=' + {0};"; EditableListButton[] buttons = new EditableListButton[] { // Botões que devem aparecer para os items da lista new EditableListButton("Editar", alterScript, ButtonTypeEnum.Edit), new EditableListButton("Excluir", removeScript, ButtonTypeEnum.Remove) }; EditableList editableList = new EditableList(configurationArea, columnNames, buttons); editableList.PreserveDefaultItem(); foreach (SmtpServer server in serverList) { String[] serverProperties = new String[] { server.name, server.address, server.port.ToString() }; Boolean isDefaultItem = server.id == defaultItemId; editableList.InsertItem(server.id, isDefaultItem, serverProperties); } editableList.DrawList(); // O clique do botão chama o script de alteração passando "id = 0", a tela de alteração // interpreta "id = 0" como "criar um novo", o id é então gerado no banco de dados. btnNovo.Attributes.Add("onClick", String.Format(alterScript, 0)); }
private static void ProcessMailingList() { DataConnector dataConnector = new DataConnector(); dataConnector.OpenConnection(); primaryServer = dataConnector.GetServer("Primary"); secondaryServer = dataConnector.GetServer("Secondary"); // Busca o servidor de envio que trabalha na porta 587 ( porta que o NET Smtp Client aceita ) SmtpServerDAO smtpServerDAO = new SmtpServerDAO(dataConnector.MySqlConnection); List <SmtpServerDTO> serverList = smtpServerDAO.GetServers("porta=587"); SmtpServerDTO smtpServer = null; if (serverList.Count == 1) { smtpServer = serverList[0]; } String listaEnvio = ""; MailingDAO mailingDAO = new MailingDAO(dataConnector.MySqlConnection); List <MailingDTO> mailingList = mailingDAO.GetMailings(null); foreach (MailingDTO mailing in mailingList) { // Verifica se hoje é o dia do faturamento Boolean isBillingTime = false; int diaFaturamento = mailing.diaFaturamento; if (diaFaturamento < 1) { diaFaturamento = 1; // Consiste o dia para casos onde o usuário entrou um número negativo ou zero } int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); if (diaFaturamento > daysInMonth) { diaFaturamento = daysInMonth; // Consiste o dia para casos onde exceda a quantidade de dias do mês } isBillingTime = (diaFaturamento == DateTime.Now.Day); // Verifica se já foi enviado hoje Boolean alreadySent = mailing.ultimoEnvio.Date == DateTime.Now.Date; if ((isBillingTime) && (!alreadySent) && (smtpServer != null)) { Boolean active = AreContractsActive(dataConnector, mailing); if (active) { SendMailing(dataConnector, mailing, smtpServer); listaEnvio += " Cliente: " + mailing.businessPartnerCode + " - " + mailing.businessPartnerName + " Enviado para: " + mailing.destinatarios + Environment.NewLine; } } } if (String.IsNullOrEmpty(listaEnvio)) { listaEnvio = "Vazia"; } if (EventLog.SourceExists("Billing Mailer")) { EventLog.WriteEntry("Billing Mailer", "Lista de envio -> " + Environment.NewLine + listaEnvio); } dataConnector.CloseConnection(); }