简体   繁体   English

Delphi Indy附件不起作用

[英]Delphi Indy Attachments not working

I have an App that needs to do some FTP uploads from a network drive. 我有一个应用程序,需要从网络驱动器上进行一些FTP上传。 I am using Indy for this. 我正在使用Indy。 Then, when a file is located on the network drive and successfully uploaded to the FTP server, I want to email this same file to a colleague. 然后,当文件位于网络驱动器上并成功上传到FTP服务器时,我想将此同一文件通过电子邮件发送给同事。

I am using the code below to do this. 我正在使用下面的代码来执行此操作。 The email gets sent fine, but for some reason, the attachments never make it. 电子邮件被发送正常,但由于某种原因,附件永远不会成功。 What am I doing wrong in my code? 我的代码中我做错了什么?

I add the file (during the FTP process) into a public (form) member variable called EmailFiles (TStringList), which I pass to a procedure. 我将文件(在FTP过程中)添加到名为EmailFiles(TStringList)的公共(表单)成员变量中,并将其传递给过程。 Here I take that list of file names and try to add it to my TIdMessage component. 在这里,我获取文件名列表并尝试将其添加到我的TIdMessage组件中。 When the email is sent, no attachments.... 发送电子邮件时,没有附件....

    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;

Don't free the Att object, and calling Msg1.MessageParts.Add won't do anything. 不要释放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;

You also need to specify the email content type: 您还需要指定电子邮件内容类型:

Msg1.ContentType := 'multipart/mixed';

Please refer to this Indy Blog , see the section "HTML and non-related attachments and no plain-text" 请参阅此Indy博客 ,请参阅“HTML和非相关附件,无明文”部分

This code is not managing the email correctly. 此代码未正确管理电子邮件。 Use something more like this instead: 使用更像这样的东西:

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;

Alternatively, you can use TIdMessageBuilderPlain to help you setup the TIdMessage correctly: 或者,您可以使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM