The official docs (Messages.attachments.get) are not very clear and they don't even mention PHP.
I am not looking for a copy/paste code but for some references that I can understand.
Context: I already understand OAuth2.0 and I am already sending e-mails successfully.
Purpose: I want to duplicate drafts. (Download attached files and create new Draft)
What did I try?
I accessed the draft and got the message id.
With that message id I fetch the attachment id.
With that attachment id I fetch the message.attachment, and get:
{
"size": 1793,
"data": "iVBORll...5CYII="
}
That "data" is the base64 encoded verison of the file, and I have the MIME Type too, so I am trying to process that.
This is the actual code of what I am doing:
$draft = $service->users_drafts->get('me', $draftId);
$borrador = (array) $draft;
$protegido = chr(0).'*'.chr(0);
$MODELAZO=$borrador[$protegido.'modelData'];
$mensaje_id=$MODELAZO['message']['id'];
$adjuntos=$MODELAZO['message']['payload']['parts'];
echo '<h1>Parte Gorda Desmenuzada:</h1>';
echo '<pre>';
print_r($adjuntos);
echo '</pre>';
echo '<h1>Archivos:</h1>';
// Qué mimetypes no son de archivos adjuntos
$mimetypezitos=array(
'image/png',
'image/jpeg',
'application/json',
'application/pdf',
'text/css'
);
foreach($adjuntos as $adjunto){
$mimetype=$adjunto['mimeType'];
if(in_array($mimetype,$mimetypezitos)){
$filename=$adjunto['filename'];
$attachmentId=$adjunto['body']['attachmentId'];
echo '<h2>Adjunto: '.$mimetype.'</h2>';
echo '<p>Nombre: '.$filename.'<p>';
echo '<p>AttID: '.$attachmentId.'<p>';
$q = 'https://www.googleapis.com/gmail/v1/users/me/messages/'.$mensaje_id.'/attachments/'.$attachmentId.'?access_token='.$_SESSION['access_token']['access_token'];
$blablason = json_decode(file_get_contents($q),true);
$base64data=$blablason['data'];
echo '<p>Data: '.$base64data.'<p>';
echo '<p>Imagen: <img src="data:image/png;base64, '.$base64data.'" alt="Base 64 Imagen" /></p>';
}
}
And there is a slight issue going on:
For the sake of testing, I am saving this info (mimetype and base64data into a db).
On a new PHP file I grab them and do:
header("Content-type: ".$mimetype);
echo base64_decode($base64data);
All images do not work. (Firefox displays black screen)
I tried with other files (.css and .json) and they are working fine. (Firefox displays the file as it originally was).