通过 SMTP 发送电子邮件时 - 如何抑制“连接正常关闭”对话框

问题描述 投票:0回答:1

如果存在某种导致网络连接关闭的情况,发送电子邮件 (SMTP) 时会显示“连接正常关闭”对话框。对话框总是出现,我似乎无法抑制它。

下面是我们用来发送电子邮件的代码,这在任何地方都适用。我们已发现导致关闭连接问题的网络问题。

我遇到的问题是,我想在发生这种情况时抑制对话框和任何潜在的异常,因为它似乎会干扰通常遵循电子邮件请求的处理。

有没有办法完全阻止对话框出现?

procedure SendEmail(Host, From, Recipients, Subject, Body, CC, BCC, ReplyTo: string;
                    Port: Integer; IsBodyHtml: Boolean);
const
  CHARSET_UTF8 = 'utf-8';
var
  IdSMTP: TIdSMTP;
  IdMessage: TIdMessage;
  builder: TIdMessageBuilderHtml;         
begin
  IdMessage := TIdMessage.Create(nil);
  try
    builder := TIdMessageBuilderHtml.Create;
    try
      // Set charsets.
      builder.PlainTextCharSet := CHARSET_UTF8;
      builder.HtmlCharSet := CHARSET_UTF8;

      // Populate the message body based on the HTML flag.
      if IsBodyHtml then
        builder.Html.Text := Body
      else
        builder.PlainText.Text := Body;   

      // Populate the message with the builder's data.
      builder.FillMessage(IdMessage);
    finally
      FreeAndNil(builder);
    end;

    // Set up email details.
    IdMessage.From.Address := From;
    IdMessage.Recipients.EMailAddresses := Recipients;
    IdMessage.Subject := Subject;
    IdMessage.CCList.EMailAddresses := CC;
    IdMessage.BccList.EMailAddresses := BCC;
    IdMessage.ReplyTo.EMailAddresses := ReplyTo;

    // Create and configure SMTP client.
    IdSMTP := TIdSMTP.Create(nil);
    try
      IdSMTP.Host := Host;
      IdSMTP.Port := Port;
      IdSMTP.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;

      // Attempt to connect and send the message.
      try
        IdSMTP.Connect;
        IdSMTP.Send(IdMessage);
      except
        on E: EIdConnClosedGracefully do
        begin
          // Suppress connection closed gracefully error dialog.
        end;
        on E: Exception do
          ShowMessage('SMTP Error: ' + E.Message);
      end;
    finally
      IdSMTP.Disconnect;
      FreeAndNil(IdSMTP);
    end;
  finally
    FreeAndNil(IdMessage);
  end;
end;
delphi indy10 delphi-10-seattle
1个回答
7
投票

该错误作为异常引发。您没有捕获异常,因此它转义到运行时,然后显示对话框。

只需在整个 SMTP 代码周围使用

try..except
块来捕获异常即可。 现在,您仅在
try..except
Connect()
调用周围有一个
Send()
,但
Disconnect()
也可以引发(因为它向服务器发送
QUIT
命令)。

Disconnect()
调用不应位于释放
finally
对象的同一个
TIdSMTP
中。

试试这个:

IdSMTP := TIdSMTP.Create(nil);
try
  IdSMTP.Host := Host;
  IdSMTP.Port := Port;
  IdSMTP.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8;

  // Attempt to connect and send the message.
  try
    IdSMTP.Connect;
    try
      IdSMTP.Send(IdMessage);
    finally
      IdSMTP.Disconnect;
    end;
  except
    on E: EIdConnClosedGracefully do
    begin
      // Suppress connection closed gracefully error dialog.
    end;
    on E: Exception do
      ShowMessage('SMTP Error: ' + E.Message);
  end;
finally
  FreeAndNil(IdSMTP);
end;
© www.soinside.com 2019 - 2024. All rights reserved.