Gmail API - send email to external recipients - gmail-api

I've developed an app (PHP) to send email from my own web service using the Gmail API. We have Gmail / Google Workspace for the company. It is possible to send emails to internal recipients.
However, I can not send emails to external recipients.
I use a service user for the authentication.
I have the user in TEST MODE.
What could I have missed?
require_once __DIR__.'/vendor/autoload.php';
function sendmail($mailto, $from, $cc, $subject, $message, $file) {
$cc = null;
$uid = md5(uniqid(time()));
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . "/credentials.json");
$client->setScopes(['https://mail.google.com']);
$client->setSubject($from);
$service = new Google_Service_Gmail($client);
$header = "From: ".$from." <".$from.">\r\n";
$header .= "Reply-To: ".$from."\r\n";
$header .= "To: ".$mailto." <".$mailto."> \r\n";
if(!is_null($cc)){ $header .= "Cc: ".$cc." <".$cc."> \r\n";}
$header .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
if(is_file($file)){
$filename = basename($file);
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/pdf; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Description:\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
}
$header .= "--".$uid."--";
$mime = rtrim(strtr(base64_encode($header), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$service->users_messages->send("me", $msg);
}
credentials.json refers to a service user

Related

import External API into function.php for wordpress

I have an API that I want to use as a reusable block in my theme.
the actual problem is that array is not a simple array like other models that I saw in here.
bellow is my code which only fetches the Whole array but does not create the HTML as i mention in Foreach () function in my code when i use [external_data] as shortcode in my theme.
defined( 'ABSPATH' ) or die( 'Unauthorized Access' );
add_shortcode('external_data', 'callback_function_name');
function callback_function_name(){
$url = 'https://api-football-standings.azharimm.site/leagues';
$object = array(
'method' => 'GET',
);
$response = wp_remote_get( $url, $object );
if ( is_wp_error( $response ) ){
$error_message = $response -> get_error_message();
return "Something went wrong: $error_message";
}
$results = json_decode( wp_remote_retrieve_body( $response ) );
var_dump($results);
$html = '';
$html .= '<table>';
$html .= '<tr>';
$html .= '<td>ID</td>';
$html .='<td>League</td>';
$html .='<td>Slug</td>';
$html .='<td>Abbr</td>';
$html .='<td>ax</td>';
$html .= '</tr/>';
foreach( $results as $result ) {
$html .= '<tr>';
$html .= '<td>' . $results->id . '</td>';
$html .= '<td>' . $results->name . '</td>';
$html .= '<td>' . $results->slug . '</td>';
$html .= '<td>' . $results->abbr . '</td>';
$html .= '<td><img src='. $results->logos->light .'/></td>';
$html .= '</tr/>';
}
$html .= '</table>';
return $html;
}

String array within JSON

going mad here, have forgot how to add and array to a JSON object in powershell :/, trying to invoke an API from powershell that requires some parameters one of these is a string array, can someone help?
$Children = #("Nanna", "Damian")
$body = #{
'parameters' = #{
'Name' = 'whatever'
'Children' = $Children
}
} | ConvertTo-Json
$body
Invoke-RestMethod -Uri $URI -Body $body -Headers $header -Method Put
but it keeps giving me this error :(
Invoke-RestMethod : {"code":"BadRequest","message":"{\"Message\":\"The request is invalid.\",\"ModelState\":{\"job.properties.
parameters.AllowedResourceTypes\":[\"An error has occurred.\"],\"job.properties.parameters.AllowedResourceTypes[0]\":[\"An err
or has occurred.\"]}}"}
believe I have done this before but cant remember how.
$Children = #{'Child1'='Nanna'
'Child2'='Damian'}
$body = #{
'parameters' = #{
'Name' = 'whatever'
'Children' = $Children
}
} | ConvertTo-Json
$body
proper Json

Invalid Signature Coinbase

I'm trying to use the API for Coinbase but I get invalid signature.
So probably I'm actually sign it wrong or I'm missing something.
what should I use on request? should i use POST or GET on method?
$urlapi = "https://api.coinbase.com/v2/time";
$Key = "--------------";
$Secret = "------------";
$fecha = new DateTime();
$timestamp = $fecha->getTimestamp();
$request="";
$body="";
$method="GET";
$Datas = $timestamp . $method . $request . $body;
$hmacSig = hash_hmac('sha256',$Datas,$Secret);
$curl = curl_init($urlapi);
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json','CB-ACCESS-KEY: '.$Key,'CB-VERSION: 2015-07-07','CB-ACCESS-TIMESTAMP: '. $timestamp,'CB-ACCESS-SIGN: '.$hmacSig));
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
curl_close($curl);
print_r($resp);
Get Current Time is a GET request (ref). The HTTP verb (GET/POST etc.) can be found in the docs for each type of request here:
In your example, the problem is that the $request variable in your message is blank. It should be $request="/v2/time";
hash_hmac returns hex encoded string by default so the hashing part is correct.
define('API_KEY', 'xxxx');
define('API_SECRET', 'xxxxxxxxx');
define('API_BASE', 'https://api.coinbase.com');
define('API_VERSION', '2015-08-31');
$headers = array(
'Content-Type: application/json',
'CB-VERSION: ' . API_VERSION
);
$url = API_BASE.'/v2/time';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
$output = json_decode($response, true);
print_r($output);
will return
Array ( [data] => Array ( [iso] => 2015-12-01T10:35:58Z [epoch] => 1448966158 ) )
You must use GET method, because is just to get some information, authentication is no needed.
This is an easier way:
$time = file_get_contents('https://api.coinbase.com/v2/time');
$time = json_decode($time);
$time = $time->data->epoch;

One character only is being returned when using foreach phpfox

I am trying to get some data from a table but when i use foreach it returns only 1 character or the 1st letter/number and one row is returned.
Here is my code.
home.class.php
public function getData()
{
$aRow = $this->database()->select('*')
->from('tablename')
->execute('getSlaveRow');
return $aRow;
}
ajax.class.php
public function getArr()
{
$data = 'No data found';
$results = Phpfox::getService('files.home')->getData();
if($results) {
$data = '<div id="fileparse" style="height:295px;overflow:auto;display:none;"</div>';
$data .= '<div id="filelist" style="height:295px;overflow:auto;">';
$data .= '<table style="width:100%;"><tr><td><b>File Name</b></td><td> <b>Account Type</b></td><td><b>Account Number</b></td><td><b>Company</b></td><td><b>Results</b></td></tr>';
foreach($results as $result) {
$data .= '<tr>';
$data .= '<td>'.$result['file'].'</td>';
$data .= '<td>'.$result['result'].'</td>';
$data .= '</tr>';
}
$data .= '</table>';
$data .= '</div>';
} else
$data = 'No results found';
$this->html('#eqblock', $data);
}
use getSlaveRows insted of getSlaveRow
getSlaveRow return single array while getSlaveRows return all rows

Send file using multipart/form-data request in php

I have image resource stored in variable which I need to send to server using its http API and PHP. I have to send request with content type multipart/form-data. So, I need to make similiar request as when form with file input and enctype=multipart/form-data attribute is sent.
I tried this:
<?php
$url = 'here_is_url_for_web_API';
$input = fopen('delfin.jpg','r');
$header = array('Content-Type: multipart/form-data');
$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_USERPWD, "user:password");
curl_setopt($resource, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
curl_setopt($resource, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($resource, CURLOPT_BINARYTRANSFER, true );
curl_setopt($resource, CURLOPT_INFILESIZE, 61631);
curl_setopt($resource, CURLOPT_INFILE, $input);
$result = curl_exec($resource);
curl_close($resource);
var_dump($result);
?>
I don't know how exactly response should look like but this returns:
http status 405
and error report is: The specified HTTP method is not allowed for the requested resource ().
use multipart/form-data and boundaries in POST content with curl.
$filenames = array("/tmp/1.jpg", "/tmp/2.png");
$files = array();
foreach ($filenames as $f){
$files[$f] = file_get_contents($f);
}
// more fields for POST request
$fields = array("f1"=>"value1", "another_field2"=>"anothervalue");
$url = "http://example.com/upload";
$curl = curl_init();
$url_data = http_build_query($data);
$boundary = uniqid();
$delimiter = '-------------' . $boundary;
$post_data = build_data_files($boundary, $fields, $files);
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post_data,
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data; boundary=" . $delimiter,
"Content-Length: " . strlen($post_data)
)
));
//
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
function build_data_files($boundary, $fields, $files){
$data = '';
$eol = "\r\n";
$delimiter = '-------------' . $boundary;
foreach ($fields as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
. $content . $eol;
}
foreach ($files as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
//. 'Content-Type: image/png'.$eol
. 'Content-Transfer-Encoding: binary'.$eol;
$data .= $eol;
$data .= $content . $eol;
}
$data .= "--" . $delimiter . "--".$eol;
return $data;
}
See the full example here: https://gist.github.com/maxivak/18fcac476a2f4ea02e5f80b303811d5f
If you work with CURL, you have to just:
1, set header 'Content-Type' as 'multipart/form-data;'
2, set option 'RETURNTRANSFER' of curl to true (use option method of curl)
3, set option 'POST' of curl to true (use option method of curl)
4, get source of your file (what you get from fopen in PHP):
$tempFile = tempnam(sys_get_temp_dir(), 'File_');
file_put_contents($tempFile, $source);
$post = array(
"uploadedFile" => "#" . $tempFile, //"#".$tempFile.";type=image/jpeg",
);
5, use post method of CURL with parameter in $post variable

Resources