简体   繁体   English

如何解决使用SMTP发送电子邮件中的错误(操作已超时)?

[英]How to fix (the operation has timed out) error in sending emails using SMTP?

I need to develop a mailing system in the intranet web-based application that I am working on it for my company. 我需要为我的公司在基于Intranet Web的应用程序中开发一个邮件系统。 I am developing it with ASP.NET and C#. 我正在用ASP.NET和C#开发它。 The purpose of this system is to let the admin to be able to send emails to the users. 该系统的目的是让管理员能够向用户发送电子邮件。 I developed this system and I tested for 25 users and it works fine. 我开发了这个系统,并为25个用户进行了测试,并且工作正常。

Now, I have 386 users in the database, so when I tried to send them emails, I got the following error: 现在,我的数据库中有386个用户,因此当我尝试向他们发送电子邮件时,出现以下错误:

Exception Details: System.Net.Mail.SmtpException: The operation has timed out. 异常详细信息:System.Net.Mail.SmtpException:操作已超时。 I think this is because of ISP in my company blocked sending email to many users after a certain number of milliseconds. 我认为这是因为我公司的ISP在一定的毫秒数后阻止向许多用户发送电子邮件。 I tried to use SendAsync but I found it will not benefit me. 我尝试使用SendAsync,但是我发现它不会使我受益。

Also, I tried to maximize the execution timeout in the Web.config file as folloiwng: 此外,我尝试将Web.config文件中的执行超时最大化,如下所示:

<location path="Email4.aspx">
        <system.web>
                <httpRuntime executionTimeout="180"/>
        </system.web>
</location>

but I failed. 但我失败了 So how to fix this problem? 那么如何解决这个问题呢?

My Code-Behind (C#): 我的代码隐藏(C#):

protected void Page_Load(object sender, EventArgs e)
    {
        SendEmailTOAllUser();
    }


    protected void SendEmail(string toAddresses, string fromAddress, string MailSubject, string MessageBody, bool isBodyHtml)
    {
        SmtpClient sc = new SmtpClient("MAIL.companyDomainName.com");
        try
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("pssp@companyDomainName.com", "PMOD Safety Services Portal (PSSP)");

            // In case the mail system doesn't like no to recipients. This could be removed
            //msg.To.Add("pssp@companyDomainName.com");

            msg.Bcc.Add(toAddresses);
            msg.Subject = MailSubject;
            msg.Body = MessageBody;
            msg.IsBodyHtml = isBodyHtml;
            //Response.Write(msg);
            sc.Send(msg);
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }

    protected void SendEmailTOAllUser()

    {
        string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspEmail;Integrated Security=True";

        using (SqlConnection conn = new SqlConnection(connString))
        {
            var sbEmailAddresses = new System.Text.StringBuilder(1000);
            string quizid = "";

            // Open DB connection.
            conn.Open();

            string cmdText = "SELECT MIN (QuizID) As mQuizID FROM dbo.QUIZ WHERE IsSent <> 1";
            using (SqlCommand cmd = new SqlCommand(cmdText, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        // There is only 1 column, so just retrieve it using the ordinal position
                        quizid = reader["mQuizID"].ToString();

                    }
                }
                reader.Close();
            }

            string cmdText2 = "SELECT Username FROM dbo.employee";
            using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        var sName = reader.GetString(0);
                        if (!string.IsNullOrEmpty(sName))
                        {
                            if (sbEmailAddresses.Length != 0)
                            {
                                sbEmailAddresses.Append(",");
                            }
                            // Just use the ordinal position for the user name since there is only 1 column
                            sbEmailAddresses.Append(sName).Append("@companyDomainName.com");
                        }
                    }
                }
                reader.Close();
            }

            string cmdText3 = "UPDATE dbo.Quiz SET IsSent = 1 WHERE QuizId = @QuizID";
            using (SqlCommand cmd = new SqlCommand(cmdText3, conn))
            {
                // Add the parameter to the command
                var oParameter = cmd.Parameters.Add("@QuizID", SqlDbType.Int);
                // Get a local copy of the email addresses
                var sEMailAddresses = sbEmailAddresses.ToString();


                    string link = "<a href='http://startQuiz.aspx?testid=" + quizid + "'> Click here to participate </a>";
                    string body = @"Good day, <br /><br />
                                <b> Please participate in the new short safety quiz </b>"
                                        + link +
                                        @"<br /><br />


                    SendEmail(sEMailAddresses, "", "Notification of New Weekly Safety Quiz", body, true);

                    // Update the parameter for the current quiz
                    oParameter.Value = quizid;
                    // And execute the command
                    cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

Here is how you can split the list: (Please notes that this is pseudo code, i have not tested it) Also, this will send an email per five users. 您可以按照以下方法拆分列表:(请注意,这是伪代码,我尚未对其进行测试)。此外,这还将每5个用户发送一封电子邮件。 You can increase the amount as you please. 您可以根据需要增加金额。

var sEMailAddresses = sbEmailAddresses.ToString();
string link = "<a href='http://pmv/pssp/StartQuiz.aspx?testid=" + quizid + "'> Click here to participate </a>";
string body = @"Good day, <br /><br />
                                <b> Please participate in the new short safety quiz </b>"
                    + link +
                    @"<br /><br />
                            Also, give yourself a chance to gain more safety culture by reading the PMOD Newsletter.
                            <br /> <br /><br /> <br />
                            This email was generated using the <a href='http://pmv/pssp/Default.aspx'>PMOD Safety Services Portal (PSSP) </a>. 
                            Please do not reply to this email.
                            ";

int sendCount = 0;
List<string> addressList = new List<string>(sEMailAddresses.Split(','));
StringBuilder addressesToSend = new StringBuilder();

for (int userIndex = 0; userIndex < addressList.Count; userIndex++)
{
    sendCount++;
    if (addressesToSend.Length > 0)
        addressesToSend.Append(",");

    addressesToSend.Append(addressList[userIndex]);
    if (sendCount == 5 || userIndex == addressList.Count - 1)
    {
        SendEmail(addressesToSend.ToString(), "", "Notification of New Weekly Safety Quiz", body, true);
        addressesToSend.Clear();
        sendCount = 0;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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