程序在 TIdAttachmentFile 构造函数处挂起

Program hangs at TIdAttachmentFile constructor

我正在使用 Delphi (Rad Studio 10.1) 编写一个 Android 程序,它将通过电子邮件(使用 SMTP 等)发送文本文件中的数据。

我目前可以发送电子邮件,但不能发送附件。使用以下代码制作附件时程序似乎冻结:

Attachment:=TIdAttachmentFile.Create(IdMessage1.MessageParts, (GetHomePath+'/test.txt'));

路径没有错,因为我可以使用以下方法将文件读入备忘录:

Memo2.Lines.LoadFromFile(GetHomePath+'/Test.txt');

这是我与附件相关的全部代码:

Text := TIdText.Create(IdMessage1.MessageParts);
Text.ContentType := 'text/plain';
Text.Body.Add('Hello!');
Attachment := TIdAttachmentFile.Create(IdMessage1.MessageParts, (GetHomePath+'/test.txt'));
with Attachment do
begin
  ContentType := 'text/plain';
  FileName := 'test.txt';
end; 
IdMessage1.ContentType := 'multipart/mixed';
AttMemory := TIdAttachmentMemory.Create(IdMessage1.MessageParts);

在此之后,我只需连接到 TIdSMTP 并发送消息。同样,在没有与 TIdAttachmentFile 相关的行的情况下发送电子邮件也没有问题。

如果我包含行

AttMemory := TIdAttachmentMemory.Create(IdMessage1.MessageParts);

我收到一封带附件的电子邮件,但是,附件没有名称,是空的,并且不能与我要附加的文件关联,因为要发送电子邮件,与附件文件相关的行必须被注释出去。

这一行:

Memo2.Lines.LoadFromFile(GetHomePath+'/Test');`

您正在加载名为 Test 的文件,而不是 test.txtLoadFromFile() 不会为您添加 .txt 文件扩展名。文件名完全按照您提供的方式使用。

如果该行确实有效,那么您确实有一个名为 Test 的文件,并且还需要将其提供给 TIdAttachmentFile

Attachment := TIdAttachmentFile.Create(IdMessage1.MessageParts, GetHomePath+'/Test');

你的标题声称冻结发生在 TIdAttachmentFile 构造函数中,但构造函数还没有访问实际文件,它只是分配了一些 属性 值(FilenameStoredPathNameFileIsTempFileContentType)。直到 TIdSMTP.Send() 需要对文件数据进行编码,才真正访问该文件。 那时,如果发生冻结,那么要么访问文件被阻止,要么网络流量被阻止,等等。如果不调试 Indy 的源代码以查看真正发生冻结的确切位置,很难诊断出这一点,因为 Send() 执行许多操作。

如果 Memo2.Lines.LoadFromFile() 有效,则另一种方法是使用 TIdText 而不是 TIdAttachmentFile,因此您可以在 [=30] 中使用相同的 LoadFromFile() 方法=] 属性:

Text := TIdText.Create(IdMessage1.MessageParts, nil);
with Text do
begin
  Body.LoadFromFile(GetHomePath+'/Test');
  ContentType := 'text/plain';
  ContentDisposition := 'attachment';
  FileName := 'test.txt';
end; 

无论如何,去掉 TIdAttachmentMemory,它对你没有任何作用,因为你没有将文件数据加载到其中。