コード例 #1
0
ファイル: SmtpServerDAO.cs プロジェクト: nicnecs/contratos
        public List <SmtpServerDTO> GetServers(String filter)
        {
            List <SmtpServerDTO> serverList = new List <SmtpServerDTO>();

            if (!String.IsNullOrEmpty(filter))
            {
                filter = " WHERE " + filter;
            }
            String          query      = "SELECT * FROM `addoncontratos`.`smtpServer`" + filter + ";";
            MySqlCommand    command    = new MySqlCommand(query, this.mySqlConnection);
            MySqlDataReader dataReader = command.ExecuteReader();

            while (dataReader.Read())
            {
                SmtpServerDTO smtpServer = new SmtpServerDTO();
                smtpServer.id            = (int)dataReader["id"];
                smtpServer.nome          = (String)dataReader["nome"];
                smtpServer.endereco      = (String)dataReader["endereco"];
                smtpServer.porta         = (int)dataReader["porta"];
                smtpServer.usuario       = (String)dataReader["usuario"];
                smtpServer.senha         = (String)dataReader["senha"];
                smtpServer.requiresTLS   = (Boolean)dataReader["requiresTLS"];
                smtpServer.defaultServer = (Boolean)dataReader["defaultServer"];

                serverList.Add(smtpServer);
            }
            dataReader.Close();

            return(serverList);
        }
コード例 #2
0
ファイル: SmtpServer.cs プロジェクト: nicnecs/contratos
        public static SmtpServer ImportFromDTO(SmtpServerDTO dtoObject)
        {
            SmtpServer server = new SmtpServer(dtoObject.nome, dtoObject.endereco, dtoObject.porta);

            server.requiresTLS = dtoObject.requiresTLS;
            server.username    = dtoObject.usuario;
            server.password    = dtoObject.senha;

            return(server);
        }
コード例 #3
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();
        }
コード例 #4
0
        private static void SendMailing(DataConnector connector, MailingDTO mailing, SmtpServerDTO server)
        {
            MailMessage mailMessage = null;

            if (mailing.codigoContrato == 0)
            {
                mailMessage = MountBusinessPartnerBilling(connector, mailing.businessPartnerCode, mailing.enviarDemonstrativo);
            }
            else
            {
                mailMessage = MountContractBilling(connector, mailing.codigoContrato, mailing.codigoSubContrato, mailing.enviarDemonstrativo);
            }

            List <String> reportFiles = null;

            if (mailing.enviarDemonstrativo && mailMessage.Attachments.Count > 0)
            {
                reportFiles = new List <String>();
                foreach (Attachment mailAttachment in mailMessage.Attachments)
                {
                    reportFiles.Add(mailAttachment.Name);
                }
            }

            // TODO:  Consertar o envio através do .NET,  utilizar algum componente que funcione, o SmtpClient
            //        da Microsoft não suporta SSL implicito
            SmtpServer smtpServer = SmtpServer.ImportFromDTO(server);
            MailSender mailSender = new MailSender(smtpServer, new TraceHandler());

            mailSender.SetContents(mailMessage.Body, reportFiles);
            Boolean success = mailSender.SendMail("Faturamento de contrato", server.usuario, mailing.destinatarios);

            if (!success)
            {
                // caso não tenha tido sucesso ao enviar através do SmtpClient do .NET tenta enviar pelo PHP
                String mailerUrl       = "http://" + primaryServer + "/Contratos/AjaxCalls/SendEmail.php";
                String mailerParams    = "subject=Faturamento%20de%20contrato&mailBody=" + mailMessage.Body + "&recipients=" + mailing.destinatarios;
                String aditionalParams = "&fileCount=0";
                if (reportFiles != null)
                {
                    aditionalParams = "&fileCount=" + reportFiles.Count;
                    int fileIndex = 0;
                    foreach (String filename in reportFiles)
                    {
                        aditionalParams += "&filename" + fileIndex + "=" + reportFiles[fileIndex];
                        aditionalParams += "&path" + fileIndex + "=" + Environment.CurrentDirectory + @"\" + reportFiles[fileIndex];
                        fileIndex++;
                    }
                }

                RequestHandler mailerRequest = new RequestHandler(mailerUrl, new TraceHandler());
                mailerRequest.StartRequest(mailerParams + aditionalParams, null);
                String mailerResponse = (String)mailerRequest.ParseResponse(typeof(System.String));

                if (mailerResponse == "Email enviado com sucesso!")
                {
                    success = true;
                }
                if (!success)
                {
                    EventLog.WriteEntry("Billing Mailer", mailerResponse);
                }
            }

            if (success) // e-mail enviado com sucesso, grava no banco de dados a data
            {
                MailingDAO mailingDAO = new MailingDAO(connector.MySqlConnection);
                mailing.ultimoEnvio = DateTime.Now;
                mailingDAO.SetMailing(mailing);
            }
        }