Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending POST request with Guzzle in Laravel

I'm trying to use ZohoMail's API to send email through my application. But it keeps giving me:

"{errorCode":"INVALID_METHOD"},"status":{"code":404,"description":"Invalid Input"}}

Here's the link to the Call that I'm trying to make: https://www.zoho.com/mail/help/api/post-send-an-email.html#Request_Body

Here's my function:

public static function sendEmail ($AccountId, $AuthCode, $FromAddress, $ToAddress, $Subject, $Content){

    $client = new Client(); //GuzzleHttp\Client
    $URI = 'http://mail.zoho.com/api/accounts/' . $AccountId . '/messages';
    $headers = ['Content-Type' => 'application/json', 'Authorization' => 'Zoho-authtoken ' . $AuthCode];
    $body = array('fromAddress' => $FromAddress, 'toAddress' => $ToAddress, 'subject' => $Subject, 'content' => $Content);
    $Nbody = json_encode($body);
    $response = $client->post($URI, $headers, $Nbody);
    echo "DONE!";

}

I've tried changing the way I'm making the call but it doesn't seem like that's the problem. I've tested the call in PostMan and it works fine so there is probably something wrong with the way I'm making the call. Any help would be much appreciated.

like image 689
Siddiqui Avatar asked Jan 04 '23 08:01

Siddiqui


2 Answers

You need to create data and headers in the same array and pass as a second argument. Use like this.

$client = new Client();
$URI = 'http://mail.zoho.com/api/accounts/'.$AccountId.'/messages';
$params['headers'] = ['Content-Type' => 'application/json', 'Authorization' => 'Zoho-authtoken ' . $AuthCode];
$params['form_params'] = array('fromAddress' => $FromAddress, 'toAddress' => $ToAddress, 'subject' => $Subject, 'content' => $Content);
$response = $client->post($URI, $params);
echo "DONE!";

Good Luck!

like image 97
Kavan Pancholi Avatar answered Jan 06 '23 00:01

Kavan Pancholi


$client = new \GuzzleHttp\Client();
$response = $client->post(
    'url',
    [
        GuzzleHttp\RequestOptions::JSON => 
        ['key' => 'value']
    ],
    ['Content-Type' => 'application/json']
);

$responseJSON = json_decode($response->getBody(), true);
like image 39
shalonteoh Avatar answered Jan 05 '23 22:01

shalonteoh