我正在使用Indy TIdHTTP 组件,并且使用以下功能成功地通过sendgrid API发送电子邮件。可以找到sendgrid api文档here。
现在我的任务是包含文件附件。在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;
答案 0 :(得分: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;