简体   繁体   中英

How to increment a variable every time i send a mail through smtp

I have a mailer and here is the code:

 private static int i=0; 
 protected void btnSubmit_Click(object sender, EventArgs e)
 {    
     ++i; //i want to increment this variable

            {
                SendHTMLMail();
            }


            void SendHTMLMail()
            {
                StreamReader reader = new StreamReader(Server.MapPath("~/one.html"));
                string readFile = reader.ReadToEnd();
                string myString = "";
                myString = readFile;



                MailMessage Msg = new MailMessage();

                Msg.From = new MailAddress(txtUsername.Text);

                Msg.To.Add(txtTo.Text);
                Msg.Subject = txtSubject.Text;
                Msg.Body = myString.ToString();
                Msg.IsBodyHtml = true;

                if (fuAttachment.HasFile)
                {
                    string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);

                    Msg.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
                }

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(txtUsername.Text, txtpwd.Text);
                smtp.EnableSsl = true;
                smtp.Send(Msg);
                Msg = null;
                ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);

                // Request both failure and success report
                Msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;

                int emailsSent = 0;

                try
                {
                    Console.WriteLine("start to send email ...");
                    smtp.Send(Msg);
                    emailsSent++;
                    Console.WriteLine("email was sent successfully!");

                }
                catch (Exception ex)
                {
                    Console.WriteLine("failed to send email with the following error:");
                    Console.WriteLine(ex.Message);
                }
            }
        }

in the above code, i have a variable 'i' and i want to increment it every time i send the mail. Now the problem i am facing is that 'i' is getting incremented only when i am sending mail again and again when my aspx page in localhost is opened. As soon as i close my aspx page, re-opens it and send the mail again, then the variable 'i' is again getting incremented to one and not to say 4 or 5.

Behavior changes where you put this code. If it's in ASPX pages, you'll loose static data whenever runtime recompile that page. If it's in DLL files, you'll loose values whenever application/IIS Pool recycles. You need to save final values into a persistent store (ie Database). Next time you need them, you must retrieve from DB, increment it then save again. Be careful, web applications are multi-thread and static variables are not thread safe. If two threads modify same variable at the same time you'll run into chaos. Use locking mechanism to access static variables in multi-threaded applications.

You need to define a separate static class for it- (because if you hit refresh / reload page in asp.net life cycle the entire page gets reloaded along with the objects.)

Define a static class (or a non static class with its constructor called) with variable/property to be incremented every time you send mail.

public static class Mail
{
       private static int mailCount;

       public static void MailSent()
       {
          mailCount++;
       }

       public static int GetMailCount()
       {
          return mailCount;
       }
}

Now in your button click use the static methods to increment and retrieve of mailCount-

protected void btnSubmit_Click(object sender, EventArgs e)
{
     Mail.MailSent(); // increments every time you send mail
     // to check how many mails sent in debug console
     System.Diagnostics.Debug.WriteLine(Mail.GetMailCount()); 
     //... YOU MAILING CODE
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM