Home > Net >  imap with curl on php
imap with curl on php

Time:09-30

I have created a very simple function:

function send($command) {
    $url = 'imaps://myImapServer';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_PORT, 993);
    curl_setopt($ch, CURLOPT_USERNAME, "MyUsername");
    curl_setopt($ch, CURLOPT_PASSWORD, "MyPassword");
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $command);

    $res = curl_exec($ch);

    return $res;
}

I can use it to query folders, but also, for example, the UID of all my messages:

echo send('UID SEARCH ALL');
# Output: * SEARCH 63 64 65 66

But for two problems I dont find a solution.

  • How do I create an array HTML Body, Text Body, Reply to,... from my outputs?

  • Why do I get the lenght of the subject with the following query, but the subject itself is not displayed?

    echo send('UID FETCH 63 BODY[HEADER.FIELDS (SUBJECT)]'); Output: * 1 FETCH (UID 63 BODY[HEADER.FIELDS (SUBJECT)] {29}

CodePudding user response:

You could try using CURLOPT_WRITEFUNCTION

curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $chunk) {
    //your imap handling here
    return strlen($chunk);
});

or if you're in a class https://www.php.net/manual/en/function.curl-setopt.php#98491

curl_setopt($this->curl_handle, 
            CURLOPT_WRITEFUNCTION, 
            array($this, "class_method_name"));

CURLOPT_WRITEFUNCTION keeps listening to your "broken up" input, feeding the chunks it has received in the callback function.

You can use the callback function to concatenate the data, push it all into an array, or just process it as you receive it, depending on what your use case is.

  • Related