4

我正在使用 Indy TIdHTTP组件,并且能够使用以下函数通过 sendgrid API 成功发送电子邮件。sendgrid api 文档可以在这里找到。

现在我的任务是包括文件附件。在 API 文档中它指出:文件内容必须是多部分 HTTP POST 的一部分

我试图修改我的函数以包含TIdMultipartFormDataStream,但没有成功。

我应该如何修改代码以支持文件附件?

procedure SendGridEmailProc;
var
  IdHTTP1: TIdHTTP;
  IdSSLIOHandlerSocket1: TIdSSLIOHandlerSocketOpenSSL;
  mString: string;
  mParams: TStringList;
  i: Integer;
begin
  try
    mParams := TStringList.Create;
    IdHTTP1 := TIdHTTP.create(nil);
    IdSSLIOHandlerSocket1 := TIdSSLIOHandlerSocketOpenSSL.create(nil);
    with IdSSLIOHandlerSocket1 do begin
      SSLOptions.Method := sslvSSLv3;
      SSLOptions.Mode :=  sslmUnassigned;
      SSLOptions.VerifyMode := [];
      SSLOptions.VerifyDepth := 2;
    end;
    with IdHTTP1 do begin
      IOHandler := IdSSLIOHandlerSocket1;
    end;


    mParams.Add('api_user=xxxxx');
    mParams.Add('api_key=xxxxx');
    mParams.Add('to=xxxxxx');
    mParams.Add('from=xxxxx');

    mParams.Add('subject=test:'+datetimetostr(now));

    mParams.Add('text=this is a test');

    IdHTTP1.Post('https://sendgrid.com/api/mail.send.xml',mParams);


  finally
    mParams.Free;
    idhttp1.free;
    IdSSLIOHandlerSocket1.Free;
  end;
end;
4

1 回答 1

3

尝试这样做(注意,它未经测试):

uses
  IdException, IdHTTP, IdSSLOpenSSL, IdMultipartFormData;

procedure SendGridEmailProc;
var
  HTTPClient: TIdHTTP;
  Parameters: TIdMultiPartFormDataStream;
  SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  HTTPClient := TIdHTTP.Create(nil);
  try
    SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    try
      SSLHandler.SSLOptions.Method := sslvSSLv3;
      SSLHandler.SSLOptions.Mode := sslmUnassigned;
      SSLHandler.SSLOptions.VerifyMode := [];
      SSLHandler.SSLOptions.VerifyDepth := 2;
      HTTPClient.IOHandler := SSLHandler;

      Parameters := TIdMultiPartFormDataStream.Create;
      try
        Parameters.AddFormField('api_user', 'xxxxx');
        Parameters.AddFormField('api_key', 'xxxxx');
        Parameters.AddFormField('to', 'xxxxxx');
        Parameters.AddFormField('from', 'xxxxx');
        Parameters.AddFormField('subject', 'test:' + DateTimeToStr(Now));
        Parameters.AddFormField('text', 'this is a test');

        // note, that you need to use the same file name for the files[]
        // identifier and that you should explicitly specify the content 
        // type for a file field to meet the HTTP dump shown in the help
        Parameters.AddFile('files[file.jpg]', 'c:\file.jpg', 
          'application/octet-stream');

        try
          HTTPClient.Post('https://sendgrid.com/api/mail.send.xml', 
            Parameters);
        except
          on E: EIdException do
            ShowMessage(E.ClassName + ': ' + E.Message);
        end;
      finally
        Parameters.Free;
      end;
    finally
      SSLHandler.Free;
    end;
  finally
    HTTPClient.free;
  end;
end;
于 2013-01-29T01:54:58.017 回答