使用 EWS API 发送电子邮件非常慢

Sending email with EWS API very slow

我下面的代码性能很差。我使用 .Net StopWatch class 找出导致运行缓慢的代码段。 这一行似乎是问题所在:

message.SendAndSaveCopy();

E.G 批处理 20 封电子邮件:发送第一封电子邮件大约需要 2 秒,此时间逐渐增加,直到发送第 20 封电子邮件,最多需要 18 秒。

public int SendBulkMarketing(bool CheckDelivery)
{
    int iCounter = 0;
    DataTable dt = null;
    try
    {
        DeliveryReportDAL myDeliveryReportDAL = new DeliveryReportDAL();
        dt = myDeliveryReportDAL.GetListMessageToSend('E');
        if (dt == null) return iCounter;
        iCounter = dt.Rows.Count;
    }
    catch (Exception ex)
    {
        new Util().LogError(ex, "SMTP:: SendBulkMarketing 1st catch");
        return 0;
    }
    if (iCounter > 0)
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
        service.Credentials = new WebCredentials(Account_UserName, Account_Password, Account_Domain);
        service.Url = new Uri(Service_URL);

        for (int I = 0; I < iCounter; ++I)
        {
            try
            {
                string myGUID = "{" + dt.Rows[I]["GUID"].ToString() + "}";
                if (IsValidEmailAddress(dt.Rows[I]["OwnerEmail"].ToString()) == false)
                {
                    DeliveryReportDAL myReport = new DeliveryReportDAL();
                    myReport.SaveSentStatus(myGUID, 'G', 3);
                    continue;
                }

                EmailMessage message = new EmailMessage(service);
                message.Subject = dt.Rows[I]["TemplateSubject"].ToString();
                message.Body = dt.Rows[I]["TemplateText"].ToString().Replace("[=12=]", " ");
                message.ToRecipients.Add(dt.Rows[I]["OwnerEmail"].ToString());
                message.IsDeliveryReceiptRequested = true;
                Guid myPropertySetId = new Guid(myGUID);

                ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId, "blablabla", MapiPropertyType.String);

                ServicePointManager.ServerCertificateValidationCallback =
                delegate(object sender1,
                         System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                         System.Security.Cryptography.X509Certificates.X509Chain chain,
                         System.Net.Security.SslPolicyErrors sslPolicyErrors)
                { return true; };

                message.SendAndSaveCopy();

                DeliveryReportDAL myReport1 = new DeliveryReportDAL();
                myReport1.SaveSentStatus(dt.Rows[I]["GUID"].ToString(), 'G', 1);
            }
            catch (Exception ex)
            {
                new Util().LogError(ex, "SMTP:: SendBulkMarketing 2nd catch");
            }
        }
    }
    return iCounter;
}

如果能帮助我提高代码性能,我将不胜感激。

此性能问题现已解决。

这是一个基本的编码问题。该问题是由 for 循环内调用的单独方法调用(未在提供的代码片段中显示)引起的。它包含性能重的功能,但不需要在 for 循环内调用。

将这个性能繁重的方法调用移到 for 循环之外解决了这个问题。