{$mode objfpc}{$H+}
uses sysutils,classes,libcurl;
const
url_imap = 'imaps://imap.gmx.net'; {wanted URL}
imap_folder = 'INBOX'; {wanted IMAP-Foldername}
user_pw = 'username:password'; {insert your username:password}
{$IFNDEF LINUX} {Windows-only: Certificate-Bundle: }
fspec_crt: PChar = 'C:\Progs\Curl\bin\curl-ca-bundle.crt';
{$ENDIF}
curl_Verb = true; {CURL with verbose output?}
FspecTmp = 'curl.tmp'; {temporary file for a mail header}
{$IFDEF LINUX}
type size_t = dword; {is on Windows in Unit system}
{$ENDIF}
var hCurl: pCurl; {= ^pointer = Curl-Handle}
function DoWrite(buf: Pointer; size: size_t; nmemb: size_t;
SS: Pointer): size_t; cdecl;
{Helper for function curl_read_file(). Writes 'size*nmemb' bytes from buffer
'buf' into a stream 'SS'. Returns the number of written bytes}
begin
result:=TStream(SS).Write(buf^,size*nmemb);
end;
function curl_read_file(url, user_pw, creq, fspecO: ansistring): CURLcode;
{reads from URL 'url' via CURL and writes the result into file 'fspecO'.
In: - user_pw = Username + Password as '<username>:<password>'.
- creq: optional custom request.
Out: returns as result the CURL-errorcode or 'CURLE_OK'}
var FS: TFileStream;
pC: pChar;
e: CURLcode;
begin
writeln('curl_read_file(): url="' + url + '", creq="' + creq + '"');
if curl_Verb then {verbose?}
curl_easy_setopt(hCurl,CURLOPT_VERBOSE,[True]);
curl_easy_setopt(hCurl,CURLOPT_URL,[PChar(url)]); {set Server-URL}
curl_easy_setopt(hCurl,CURLOPT_USERPWD,[PChar(user_pw)]); {set user + pw}
{$IFNDEF LINUX}
curl_easy_setopt(hCurl,CURLOPT_CAINFO,[fspec_crt]); {set Certificate-Bundle}
{$ENDIF}
if creq <> '' then pC:=PChar(creq) {optional Custom Request: }
else pC:=nil;
curl_easy_setopt(hCurl,CURLOPT_CUSTOMREQUEST,[pC]);
FS:=TFileStream.Create(fspecO,fmCreate); {output into a file: }
curl_easy_setopt(hCurl,CURLOPT_WRITEFUNCTION,[@DoWrite]);
curl_easy_setopt(hCurl,CURLOPT_WRITEDATA,[Pointer(FS)]);
e:=curl_easy_perform(hCurl); {execute CURL-command}
FS.Free;
writeln('Result1=', e);
exit(e);
end;
function Test_read_IMAP(nr: integer): CURLcode;
{reads the Header of Mail number 'nr' into file 'FspecTmp' and returns as
result the CURL-errorcode or 'CURLE_OK'}
var url: ansistring;
e: CURLcode;
begin
url:=url_imap + '/' + imap_folder + '/;UID=' + IntToStr(nr)
+ '/;SECTION=HEADER'; {read only the Header}
hCurl:=curl_easy_init; {initialize CURL}
if not system.Assigned(hCurl) then exit(CURLE_FAILED_INIT);
try e:=curl_read_file(url,user_pw,'',FspecTmp);
finally
curl_easy_cleanup(hCurl);
end; {try}
exit(e);
end;
var e: CURLcode;
begin {main}
e:=Test_read_IMAP(1); {reads mail-header from the 1st mail}
writeln('Result2=', e);
end.