Delphi Indy附件无法正常工作

3

我有一个需要从网络驱动器上传一些FTP的应用程序。我正在使用Indy进行操作。然后,当在网络驱动器上找到文件并成功上传到FTP服务器时,我想将同样的文件通过电子邮件发送给同事。

我使用下面的代码来实现这个功能。电子邮件可以成功发送,但是附件却无法传送。请问我的代码有什么问题?

我将文件(在FTP过程中)添加到称为EmailFiles(TStringList)的公共(表单)成员变量中,然后将其传递给一个过程。在这里,我获取文件名列表并尝试将其添加到我的TIdMessage组件中。当发送电子邮件时,没有附件……

    procedure TfrmMain.SendEmail(FromMail, ToMail, Subject, Body: String;
  Attachments: TStringList);
var
  i: Integer;
  Att : TIdAttachmentFile;
begin
   Memo1.Lines.Add('');
   Memo1.Lines.Add('Starting Email service...');
   SMTP.Host := 'mail.*****.com';
   SMTP.Username := '***UN***';
   SMTP.Password := '***PW***';
   try
     Msg1.From.Address := FromMail;
     Msg1.Recipients.EmailAddresses := ToMail;
     Msg1.Subject := Subject;
     Msg1.Body.Add(Body);

     //Add attachment(s)
     if Attachments.Count <= 0 then Memo1.Lines.Add('Warning: Cannot detect attachments for the Email...');

     for i := 0 to Attachments.Count - 1 do
       begin
          if FileExists(Attachments[i]) then
            begin
              //Memo1.Lines.Add('Adding Attachment ' + Msg1.MessageParts.Items[0].FileName + '...');
              Att := TIdAttachment.Create(Msg1.MessageParts, Attachments[i]);
              Msg1.MessageParts.Add;  //an attempt to explicitly ADD the Att object, to no avail
              Memo1.Lines.Append('Added Attachment ' + Attachments[i]);
              Att.Free;
            end
          else
            begin
              Memo1.Lines.Add('Could not locate file: ' + Attachments[i] + ' for Email attachment!');
            end;
       end;

       //Try to send the message
       try
         SMTP.Connect;
         if Msg1.MessageParts.AttachmentCount > 0 then begin
           SMTP.Send(Msg1);
           Memo1.Lines.Add('Sent Email successfully!');
         end
          else begin
            if Messagedlg('Do you want to send the Email without attachments?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
              begin
                SMTP.Send(Msg1);
                Memo1.Lines.Add('Sent Email successfully, without attachments!');
              end
            else
              Memo1.Lines.Add('No files attached to the Email Message - Cannot send!');
          end;

       except
         on E:Exception do
           begin
             Messagedlg('Could not send the Email Message!' + #13#10 + E.Message, mtError, [mbOK], 0);
           end;
       end;

   except
     on E:Exception do
       ShowMessage('Could not connect to SMTP Server' + #13#10 + E.Message);
   end;
end;

也许值得一提的是,在Indy 10中,以下代码对我来说不起作用:(由于create具有1个集合参数)Att := TIdAttachmentFile.Create(Msg1.MessageParts, Attachments[i]);基本上修复这个问题的方法是:with TIdAttachmentFile.Create(Msg1.MessageParts) do begin FileName := Attachments[i]; end; - T.S
2个回答

2

不要释放Att对象,而且调用Msg1.MessageParts.Add也不会有任何作用。

if FileExists(Attachments[i]) then
begin      
  TIdAttachment.Create(Msg1.MessageParts, Attachments[i]);
end
else
begin
  Memo1.Lines.Add('Could not locate file: ' + Attachments[i] + ' for Email attachment!');
end;

你需要指定电子邮件内容的类型:
Msg1.ContentType := 'multipart/mixed';

请参考这篇Indy博客,查看“HTML和非相关附件以及无纯文本”部分。

除非正文是指附件,否则您应该使用 Msg1.ContentType := 'multipart/related'; - mezen
这篇博客文章旨在介绍如何设置TIdMessage以便发送带有附件的HTML格式电子邮件,但是原帖发送的是带有附件的纯文本格式电子邮件。该文章并未涵盖此特定设置。 - Remy Lebeau

2

这段代码没有正确管理邮件。建议使用以下代码:

procedure TfrmMain.SendEmail(FromMail, ToMail, Subject, Body: String;
  Attachments: TStringList);
var
  i: Integer;
  Att : TIdAttachmentFile;
begin
  Memo1.Lines.Add('');
  Memo1.Lines.Add('Starting Email service...');

  try
    Msg1.Clear;
    Msg1.From.Address := FromMail;
    Msg1.Recipients.EmailAddresses := ToMail;
    Msg1.Subject := Subject;

    // note, if attachments are being sent, the Body needs to
    // be added as a TIdText in the Msg1.MessageParts collection.
    // If ConvertPreamble is true, Msg1.Body is moved to a
    // TIdText for you during sending...
    Msg1.ConvertPreable := True;
    Msg1.Body.Text := Body;

    //Add attachment(s)
    if Attachments.Count = 0 then
      Memo1.Lines.Add('Warning: Cannot detect attachments for the Email...');

    for i := 0 to Attachments.Count - 1 do
    begin
      if FileExists(Attachments[i]) then
      begin
        //Memo1.Lines.Add('Adding Attachment ' + Attachments[i] + '...');
        Att := TIdAttachmentFile.Create(Msg1.MessageParts, Attachments[i]);
        // set properties of Att as needed...
        Memo1.Lines.Append('Added Attachment ' + Attachments[i]);
        // DO NOT free Att here! It will be freed when
        // the TIdMessage is cleared/freed...
      end
      else
      begin
        Memo1.Lines.Add('Could not locate file: ' + Attachments[i] + ' for Email attachment!');
      end;
    end;

    Msg1.MessageParts.CountParts;
    if Msg1.MessageParts.AttachmentCount = 0 then
    begin
      if MessageDlg('Do you want to send the Email without attachments?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
      begin
        Memo1.Lines.Add('No files attached to the Email Message - Cannot send!');
        Exit;
      end;
      // only the Body is being sent
      Msg1.ContentType := 'text/plain';
    end else
    begin
      // Body and Attachments are being sent
      Msg1.ContentType := 'multipart/mixed';
    end;
  except
    on E: Exception do
    begin
      MessageDlg('Could not prepare the Email Message!' + #13#10 + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  //Try to send the message

  SMTP.Host := 'mail.*****.com';
  SMTP.Username := '***UN***';
  SMTP.Password := '***PW***';

  try
    SMTP.Connect;
  except
    on E: Exception do
    begin
      MessageDlg('Could not connect to SMTP Server!' + #13#10 + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  try
    try
      SMTP.Send(Msg1);
    finally
      SMTP.Disconnect;
    end;
  except
    on E: Exception do
    begin
      MessageDlg('Could not send the Email Message!' + #13#10 + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  if Msg1.MessageParts.AttachmentCount > 0 then begin
    Memo1.Lines.Add('Sent Email successfully!');
  end else begin
    Memo1.Lines.Add('Sent Email successfully, without attachments!');
  end;
end;

或者,您可以使用TIdMessageBuilderPlain来帮助您正确设置TIdMessage

uses
  ..., IdMessageBuilder;

procedure TfrmMain.SendEmail(FromMail, ToMail, Subject, Body: String;
  Attachments: TStringList);
var
  i: Integer;
  Bldr: TIdMessageBuilderPlain;
begin
  Memo1.Lines.Add('');
  Memo1.Lines.Add('Starting Email service...');

  try
    Msg1.Clear;
    Msg1.From.Address := FromMail;
    Msg1.Recipients.EmailAddresses := ToMail;
    Msg1.Subject := Subject;

    Bldr := TIdMessageBuilderPlain.Create;
    try
      Bldr.PlainText.Text := Body;

      //Add attachment(s)
      if Attachments.Count = 0 then
        Memo1.Lines.Add('Warning: Cannot detect attachments for the Email...');

      for i := 0 to Attachments.Count - 1 do
      begin
        if FileExists(Attachments[i]) then
        begin
          //Memo1.Lines.Add('Adding Attachment ' + Attachments[i] + '...');
          Bldr.Attachments.Add(Attachments[i]);
          Memo1.Lines.Append('Added Attachment ' + Attachments[i]);
        end
        else
        begin
          Memo1.Lines.Add('Could not locate file: ' + Attachments[i] + ' for Email attachment!');
        end;
      end;

      if Bldr.Attachments.Count = 0 then
      begin
        if MessageDlg('Do you want to send the Email without attachments?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
        begin
          Memo1.Lines.Add('No files attached to the Email Message - Cannot send!');
          Exit;
        end;
      end;

      Bldr.FillMessage(Msg1);
    finally
      Bldr.Free;
    end;
  except
    on E: Exception do
    begin
      MessageDlg('Could not prepare the Email Message!' + #13#10 + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  //Try to send the message

  SMTP.Host := 'mail.*****.com';
  SMTP.Username := '***UN***';
  SMTP.Password := '***PW***';

  try
    SMTP.Connect;
  except
    on E: Exception do
    begin
      MessageDlg('Could not connect to SMTP Server!' + #13#10 + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  try
    try
      SMTP.Send(Msg1);
    finally
      SMTP.Disconnect;
    end;
  except
    on E: Exception do
    begin
      MessageDlg('Could not send the Email Message!' + #13#10 + E.Message, mtError, [mbOK], 0);
      Exit;
    end;
  end;

  if Msg1.MessageParts.AttachmentCount > 0 then begin
    Memo1.Lines.Add('Sent Email successfully!');
  end else begin
    Memo1.Lines.Add('Sent Email successfully, without attachments!');
  end;
end;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接