gpt4 book ai didi

delphi - 使用Indy TidHttp组件通过sendgrid发送电子邮件文件附件

转载 作者:行者123 更新时间:2023-12-03 15:54:50 24 4
gpt4 key购买 nike

我正在使用 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;

最佳答案

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

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;

关于delphi - 使用Indy TidHttp组件通过sendgrid发送电子邮件文件附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com