首页 > 解决方案 > 每次通过 smtp 发送邮件时如何增加变量

问题描述

我有一个邮件程序,代码如下:

 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);
                }
            }
        }

在上面的代码中,我有一个变量“i”,我想在每次发送邮件时递增它。现在我面临的问题是,只有当我在 localhost 中的 aspx 页面打开时我一次又一次地发送邮件时,'i'才会增加。一旦我关闭我的 aspx 页面,重新打开它并再次发送邮件,变量“i”就会再次增加到 1,而不是说 4 或 5。

标签: c#.netsmtpincrement

解决方案


放置此代码的位置会发生行为变化。如果它在 ASPX 页面中,那么每当运行时重新编译该页面时,您都会丢失静态数据。如果它在 DLL 文件中,那么只要应用程序/IIS 池回收,您就会丢失值。您需要将最终值保存到持久存储(即数据库)中。下次你需要它们时,你必须从数据库中检索,增加它然后再次保存。请注意,Web 应用程序是多线程的,静态变量不是线程安全的。如果两个线程同时修改同一个变量,您将陷入混乱。使用锁定机制访问多线程应用程序中的静态变量。


推荐阅读