-3

I have written a code which sends mail to the admin for moderation whenever a user adds a content from front end.....the problem is sometimes the admin gets two mails of same content.

below is my code

            MailMessage mail = new MailMessage();

            string mailto = ConfigurationManager.AppSettings["adminStoryEmail"].ToString();
            mail.To.Add(mailto);
            //mail.To.Add("vidyasagar.patil@viraltech.in");
            mail.From = new MailAddress(ConfigurationManager.AppSettings["fromEmail"]);
            mail.Subject = ConfigurationManager.AppSettings["email_subject"];
            if (uploadedpath != "")
            {
                mail.Body = "Email ID : " + txtEmail.Text + "<br /> Title : " + txtStoryTitle.Text + "<br />" + " Download :   " + " http://www.achievewithdell.in/uploads/" + uploadedpath + "<br />";
                if (story != "")
                {
                    mail.Body += "New story has been added" + " http://www.achievewithdell.in/admin/ManageStory.aspx";
                }
            }
            else
            {
                mail.Body = "Email ID : " + txtEmail.Text + "<br /> Title : " + txtStoryTitle.Text + " <br />";
                if (story != "")
                {
                    mail.Body += "New story has been added" + " http://www.achievewithdell.in/admin/ManageStory.aspx";
                }
            }
            mail.IsBodyHtml = true;

            SmtpClient smtp = new SmtpClient();
            smtp.Host = ConfigurationManager.AppSettings["smtp_host"];  //Or Your SMTP Server Address
            smtp.Port = 25;
            smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["smtp_userid"], ConfigurationManager.AppSettings["smtp_password"]); //Or your Smtp Email ID and Password
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

            smtp.Send(mail);
vidyasagar85
  • 131
  • 1
  • 2
  • 11

2 Answers2

1

You say sometimes the email gets sent twice. This would suggest the code you've given us is fine, the problem probably lies with what calls that code.

One way you could eliminate duplicates is to queue up your mails to be sent, perhaps in a database (storing: to, from, subject, body etc). Then periodically, iterate through mails to be sent, ignoring duplicates and marking sent mails so they don't get sent again.

Failing a refactor to your application like that, as the other poster suggested, get out your debugger and set a breakpoint. Depending on your version of Visual Studio, you could use the Breakpoint Hit Count so you only land at the breakpoint on the 2nd time.

Phil Cooper
  • 3,083
  • 39
  • 63
0

Debug and make sure smtp Send() method is not called twice, put a break point on that line.

sandip
  • 70
  • 4