我之前问过关于通过 GMail 使用 Indy 发送带有附件的电子邮件的问题,我很高兴地说基本代码可以正常工作。但是,我注意到发送附件需要几分钟,并且在那段时间内,程序会冻结(即使我在程序中添加了 TIdAntiFreeze 组件)。我认为让电子邮件由单独的线程发送是个好主意,从而使程序能够响应。
我一直无法在网上找到显示如何从线程发送电子邮件的代码,因此我不得不编写自己的代码,但只能部分工作。
我从发送电子邮件的表单中删除了 SMTP 组件;相反,我将电子邮件组件的数据保存到磁盘(使用 TIdMessage.SaveToFile 方法),然后创建一个非模态对话框,该对话框创建一个线程来实例化所需的组件并发送电子邮件。我想为 SMTP 和 IdMessage 组件创建事件处理程序,但不知道如何在运行时执行此操作 - 线程代码无法访问任何表单方法。
虽然我正在展示我的代码,但我更希望看到一些可以正常工作的东西。
unit Manage77c;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SizeGrip, ManageForms, ExtCtrls, StdCtrls, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase,
IdMessageClient, IdSMTPBase, IdSMTP, IdIOHandler, IdIOHandlerSocket, IdSSL,
IdIOHandlerStack, IdMessage, IdSSLOpenSSL;
type
TSendAMail = class(TForm)
mem: TMemo;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
public
constructor create (const s: string);
end;
implementation
{$R *.dfm}
var
ahost, apassword, ausername, curstatus, fn: string;
caller: thandle;
function DoEmail (p: pointer): longint; stdcall;
var
ssl: TIdSSLIOHandlerSocketOpenSSL;
email: TIdMessage;
begin
caller:= THandle (p);
email:= TIdMessage.create;
with email do
begin
loadfromfile (fn);
// OnInitializeISO:= ??
end;
deletefile (fn);
ssl:= TIdSSLIOHandlerSocketOpenSSL.create;
ssl.SSLOptions.SSLVersions:= [sslvTLSv1];
with TIdSMTP.create do
try
//OnStatus:= ??
iohandler:= ssl;
host:= ahost;
password:= apassword;
username:= ausername;
port:= 587;
useTLS:= utUseExplicitTLS;
Connect;
try
Send (email);
except
on E:Exception do;
end;
finally
Disconnect;
free
end;
ssl.free;
email.free;
result:= 0
end;
constructor TSendAMail.Create (const s: string);
var
empty: boolean;
thrid: dword;
begin
inherited create (nil);
fn:= s;
repeat
with dm.qGetSMTP do // this part gets the SMTP definitions from the database
begin
open;
aHost:= fieldbyname ('smtphost').asstring;
ausername:= fieldbyname ('smtpuser').asstring;
apassword:= fieldbyname ('smtppass').asstring;
close
end;
empty:= (ahost = '') or (ausername = '') or (apassword = '');
if empty then
with TGetSMTP.create (nil) do // manage77a
try
execute
finally
free
end;
until not empty;
CreateThread (nil, 0, @DoEmail, pointer (self.handle), 0, thrid);
close
end;
procedure TSendAMail.FormClose(Sender: TObject; var Action: TCloseAction);
begin
action:= caFree
end;
end.