电子邮件工作正常,但同时收到两封电子邮件?

时间:2018-06-17 08:46:48

标签: c# windows windows-services

我尝试发送电子邮件,下面的代码工作正常但电子邮件一次发送两次。我尝试了很多,但我不知道我犯了什么错误。

RTElapsedTime.cs:

   public void Elapsed()
        {
            T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);
            T1.Interval = 60000;
            T1.Enabled = true;
        }

        public void T1_Elapsed(object source, ElapsedEventArgs e)
        {
            try
            {
                MatchingTime = DateTime.Now.ToString("HH:mm");
                EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
                DataTable dt = EmailMgr.EmailServiceScheduleTimeIntervalRunTime(MatchingTime.ToString());
                TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count : " + dt.Rows.Count);
                foreach (DataRow r in dt.Rows)
                {
                    T1.Enabled = false;
                    RTEmailManagement(r);
                    T1.Enabled = true;
                }
                TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Tasks are completed.");
            }
            catch (Exception ex)
            {
                TraceImplogs.TraceLTService(ex.Message);
            }
        }
        DataTable dataRPT1 = new DataTable();
        public DataTable ReportGeneration2(EmailDTO EETO)
        {
            EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
            dataRPT1 = EmailMgr.EmailLatearrivalReport(EETO.Departments, "0", EETO.ReportType);
            return dataRPT1;

        }
        public void RTEmailManagement(DataRow dr)
        {
            EDTO = null;
            EDTO = new EmailDTO();
            MatchingTime = DateTime.Now.ToString("HH:mm");
            EDTO.SecondTime = MatchingTime;

            EDTO.ScheduleTime = dr["rshtime"].ToString();
            EDTO.ToEmails = dr["rsh_altrntmail"].ToString();
            EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';');

            EDTO.Subject = dr["rsh_subjct"].ToString();
            EDTO.ReportID = dr["reportid"].ToString();
            EDTO.Departments = dr["rsh_dept"].ToString();
            EDTO.ReportType = Convert.ToInt32(dr["rsh_typly"].ToString());
            EDTO.weekly = dr["rsh_day"].ToString();
            EDTO.Monthly = dr["rsh_dayofmnth"].ToString();
            EDTO.Day = dr["xday"].ToString();
            EDTO.Body = dr["rsh_body"].ToString();
            EDTO.langcode = Convert.ToInt32(dr["langcode"].ToString());
            CompanyID = Int32.Parse(dr["Company_id"].ToString());
            dataRPT1 = ReportGeneration2(EDTO);
            TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count---- : " + dataRPT1.Rows.Count);
            foreach (DataRow r in dataRPT1.Rows)
            {

                EDTO.CcEmails = new List<string>(EDTO.CcEmails) { r["Manager"].ToString() }.ToArray();
                EDTO.CcEmails = EDTO.CcEmails.Distinct().ToArray();
                //EDTO.CcEmails[EDTO.CcEmails.Length-1] = dataRPT1.Rows[k]["Manager"].ToString();
                EDTO.ToEmails1 = r["email_addr"].ToString();
                EDTO.LateArrival = r["LateArrivals"].ToString();
                if (EDTO.ScheduleTime == EDTO.SecondTime)
                {
                    TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "time matched");
                    switch (Convert.ToInt32(EDTO.ReportType))
                    {

                        case 0:
                        case 1:

                            EmailConfiguration(CompanyID, EDTO);

                            break;

                        case 2:
                            //TraceImplogs.TraceLTService("tyoe 2 new");
                            EmailConfiguration(CompanyID, EDTO);
                            break;
                        case 3:
                            //  TraceImplogs.TraceLTService("tyoe 3 new");
                            EmailConfiguration(CompanyID, EDTO);
                            break;
                        default:
                            break;
                    }
                }
            }
            // else TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "not matching");
        }

        public void EmailConfiguration(int compid, EmailDTO EDTO)
        {
            try
            {
                ConfigDTO mlDTO = new ConfigDTO();
                EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString);
                DataTable EmailConfigDT = EmailMgr.SelectAllCompanyEmailConfiguration(compid);
                RTMailProcessing Mprocess = new RTMailProcessing();
                mlDTO.ConfigMail = EmailConfigDT.Rows[0]["comp_email"].ToString();
                mlDTO.ConfigPwd = EmailConfigDT.Rows[0]["comp_pwd"].ToString();
                mlDTO.ConfigHost = EmailConfigDT.Rows[0]["host_name"].ToString();
                mlDTO.ConfigPort = Convert.ToInt32(EmailConfigDT.Rows[0]["host_port"].ToString());

                Mprocess.EmailProcessing(mlDTO, EDTO);


            }
            catch (Exception ex)
            {
                TraceImplogs.TraceLTService(ex.Message + "  Email Error");
            }
        }

电子邮件处理cs代码。

RtMailprocessing.cs:

 public void EmailProcessing(ConfigDTO conDTO, EmailDTO EDTO)
    {
        RTMsg.language(EDTO.langcode);
        conDTO.ConfigPwd = utility.Decrypt_Secure_Keylock(conDTO.ConfigPwd);
        // TraceImplogs.TraceLTService("Entered Config file" + conDTO.ConfigPwd);
        SmtpClient smtp = new SmtpClient
        {
            Host = conDTO.ConfigHost,
            Port = conDTO.ConfigPort,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,

            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential(conDTO.ConfigMail, conDTO.ConfigPwd)
            // Timeout = 30000,
        };
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
        //  TraceImplogs.TraceLTService("Entered inside");
        if (EDTO.ToEmails != "")
        {
            using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(conDTO.ConfigMail, EDTO.ToEmails1, EDTO.Subject, EDTO.Body))
            {
                for (int k = 0; k < EDTO.CcEmails.Length; k++)
                {
                    if (EDTO.CcEmails[k] != "")
                    {
                        message.CC.Add(EDTO.CcEmails[k].TrimEnd(';'));
                    }
                    else
                    {
                        TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Ccmails are empty");
                    }
                }
                message.CC.Add(EDTO.ToEmails);
                message.Subject = ""; message.Body = "";
                message.Subject = EDTO.Subject;
                message.SubjectEncoding = System.Text.Encoding.UTF8;
               // ReportGeneration(EDTO);
                string EmailBody = "";
                if (attach != null)
                {
                    message.Attachments.Add(attach);

                    string[] RepBody = EDTO.Body.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                    /*****with attachment***/
                    foreach (string lines in RepBody)
                    {
                        EmailBody += "<p style='font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; margin-left: 10px'>" + lines + "</p>";
                    }
                    message.Body = "Email Testing";
                    message.BodyEncoding = System.Text.Encoding.UTF8;
                    //message.Attachments.Dispose();

                    //message.Dispose();
                }
                if (dataRPT.Rows.Count < 1)
                {
                    message.Body ="Test Email";
                    message.BodyEncoding = System.Text.Encoding.UTF8;
                    message.Attachments.Clear();
                }
                message.IsBodyHtml = true; //Send this as plain-text

                smtp.Send(message);
                TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + NameRPT + " sent successfully.");
                message.CC.Clear();
                //((IDisposable)smtp).Dispose();
                //message.Attachments.Dispose();
                //message.Dispose();
            }
        }
    }

当我使用断点循环调试时只运行一次,但我收到了两封电子邮件。我不知道我犯了什么错误。

提前致谢。

1 个答案:

答案 0 :(得分:1)

我要猜测,你不能取消订阅活动:

T1.Elapsed += new ElapsedEventHandler(T1_Elapsed);

您需要取消订阅:

T1.Elapsed -= new ElapsedEventHandler(T1_Elapsed);

电子邮件服务器处理了这两封邮件并同时发送。