Письмо не отправлено до закрытия приложения - PullRequest
2 голосов
/ 25 мая 2010

У меня есть приложение, которое использует SmtpClient для отправки электронной почты, но сообщения электронной почты не отправляются, пока приложение не закроется. Я искал и искал решение проблемы, но не смог найти.

В системе установлен антивирус Symantec, что может быть проблемой.

У кого-нибудь есть решение этой проблемы?

Вот код, который я использую.

public class EMail
{
    private string server;
    public string Server {get{return this.server;}set{this.server = value;}}
    private string to;
    public string To {get{return this.to;}set{this.to = value;}}
    private string from;
    public string From {get{return this.from;}set{this.from = value;}}
    private string subject;
    public string Subject {get{return this.subject;}set{this.subject = value;}}
    private string body;
    public string Body {get{return this.body;}set{this.body = value;}}

    public EMail()
    {}
    public EMail(string _server, string _to, string _from, string _subject, string _body)
    {
        this.Server = _server;
        this.To = _to;
        this.From = _from;
        this.Subject = _subject;
        this.Body = _body;
    }   

    public void Send()
    {
        using(System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(this.From, this.To, this.Subject, this.Body))
        {        
            message.IsBodyHtml = true;
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(this.Server);
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            //I have tried this, but it still does not work.
            //client.ServicePoint.ConnectionLeaseTimeout = 0;
            try 
            {
                client.Send(message);
            }  
            catch(System.Exception ex) 
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());              
            }
        }
    }
}

Edit:

Оказывается, электронное письмо в конце концов отправляется через 2-3 минуты. Похоже, что он находится в очереди на сервере Exchange, или соединение SmtpClient в конечном итоге истекает и закрывается сервером.

Edit:

Я пытался.

client.ServicePoint.ConnectionLeaseTimeout = 1;
client.ServicePoint.MaxIdleTime = 1;

Ответы [ 6 ]

5 голосов
/ 26 мая 2010

Я наконец; В конце концов, помощь от StackOverflow и других источников исследования нашла решение При установке System.Net.ServicePointManager.MaxServicePointIdleTime = 1 почта отправляется немедленно.

Вот окончательный код.

public class EMail
{
    private string server;
    public string Server {get{return this.server;}set{this.server = value;}}
    private string to;
    public string To {get{return this.to;}set{this.to = value;}}
    private string from;
    public string From {get{return this.from;}set{this.from = value;}}
    private string subject;
    public string Subject {get{return this.subject;}set{this.subject = value;}}
    private string body;
    public string Body {get{return this.body;}set{this.body = value;}}

    public EMail()
    {}
    public EMail(string _server, string _to, string _from, string _subject, string _body)
    {
        this.Server = _server;
        this.To = _to;
        this.From = _from;
        this.Subject = _subject;
        this.Body = _body;
    }   

    public void Send()
    {
        using(System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(this.From, this.To, this.Subject, this.Body))
        {        
            message.IsBodyHtml = true;
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(this.Server);
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

            int temp = System.Net.ServicePointManager.MaxServicePointIdleTime; //<- Store the original value.
            System.Net.ServicePointManager.MaxServicePointIdleTime = 1; //<- Change the idle time to 1.

            try 
            {
                client.Send(message);
            }  
            catch(System.Exception ex) 
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());              
            }
            finally
            {
                System.Net.ServicePointManager.MaxServicePointIdleTime = temp; //<- Set the idle time back to what it was.
            }
        }
    }
}

Спасибо всем за помощь! Особенно ледяной человек.

3 голосов
/ 25 мая 2010

Возможная причина заключается в том, что соединение остается открытым. Попробуйте закрыть соединение в конце метода Send и посмотрите, работает ли оно.

Редактировать: Это похоже на ситуацию в .NET 4.0 теперь, когда SmtpClient реализует IDispose.

2 голосов
/ 25 мая 2010

Бьюсь об заклад, у вас установлен антивирус Norton. Кажется, это известная проблема с Norton Antivirus. Это можно исправить, открыв антивирус Norton и отключив инструменты электронной почты. Дайте мне знать, если это работает для вас.

1 голос
/ 25 мая 2010

ок Тестер ... Если вы хотите обойти проблему Нортона, все довольно просто. Добавьте следующую строку:

message.EnableSsl = true;

Это приведет к тому, что клиент smtp зашифрует ваше соединение, отправив его на другой порт, отличный от того, который отслеживает norton. Посмотрите, работает ли это!

0 голосов
/ 25 мая 2010

System.Net.Mail.MailMessage и System.Net.Mail.SmtpClient оба реализуют IDisposable, что означает, что вам нужно вызвать Dispose после того, как вы закончите. IE:

using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(this.From, this.To, this.Subject, this.Body))
{
    message.IsBodyHtml = true; 
    using(System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(this.Server))
    {
        client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 
        try  
        { 
            client.Send(message); 
        }   
        catch(System.Exception ex)  
        { 
            System.Windows.Forms.MessageBox.Show(ex.ToString());               
        }
    }
} 
0 голосов
/ 25 мая 2010

Кроме того, для любых одноразовых типов, таких как System.Net.Mail.MailMessage, вы должны использовать блок «using»:

public void Send() 
{ 
    using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(this.From, this.To, this.Subject, this.Body))
    {
        message.IsBodyHtml = true; 
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(this.Server); 
        client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 
        try  
        { 
            client.Send(message); 
        }   
        catch(System.Exception ex)  
        { 
            System.Windows.Forms.MessageBox.Show(ex.ToString());               
        }
    } 
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...