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

时间:2017-01-19 14:37:41

标签: c# exchangewebservices ews-managed-api

我的代码表现非常糟糕。我使用.Net StopWatch类来找出导致缓慢的代码片段。 这条线似乎是个问题:

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("\0", " ");
                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;
}

我非常感谢在提高代码性能方面的任何帮助。

1 个答案:

答案 0 :(得分:0)

此问题现已解决。

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

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