Google Apps Engine PHP Mail API - $image_data - php

in the official GAE PHP Mail Api doc https://cloud.google.com/appengine/docs/php/mail/ they show this example:
use \google\appengine\api\mail\Message;
// Notice that $image_data is the raw file data of the attachment.
try
{
$message = new Message();
$message->setSender("from#google.com");
$message->addTo("to#google.com");
$message->setSubject("Example email");
$message->setTextBody("Hello, world!");
$message->addAttachment('image.jpg', $image_data, $image_content_id);
$message->send();
} catch (InvalidArgumentException $e) {
// ...
}
but they dont explain how to fill $image_data with an uploaded static file.
any help ? if it can be explicit it will be great
thanks
diego

Use file_get_contents() to retrieve the data you want to send as part of the email.
$image_data = file_get_contents('path/to/static/file.jpg');
Or you can send an image stored in Cloud Storage
$image_data = file_get_contents('gs://my_bucket/path/to/file.jpg');

Related

FD Table is full error while sending email using SES

I'm trying to send 2K emails to my customers. I'm using Amazon SES to send the email using this library. When I try to send the email with the attachment, I'm getting SimpleEmailService::sendEmail(): 35 Process open FD table is full error. I just followed the instruction given in the readme file. And changed credentials only. Any help will be appreciated... :)
Edit
Almost 900 emails with the attachment sent successfully. But after that, it starts throwing the error.
The attachment is of type PDF.
Edit 2
The service team says that you are not closing the file descriptor after sending the mails. You need to close the file descriptor after the job is done. That way it wont exhaust the limit set on the number of FDs assigned
Here is the code I'm trying.
$mails = [
'customer#email.com'
...
...
...
];
$ses = new SimpleEmailService('XXXXXXX', 'XXXXXXX');
$ses->enableVerifyPeer(false);
$m = new SimpleEmailServiceMessage();
foreach ($mails as $email) {
try {
$m->setFrom('From <example#email.com>');
$m->setSubject('Subject');
$m->setMessageFromString('','<p>This is the test email.</p>');
$m->addTo($email);
$atch = path to pdf;
$mime_type = #mime_content_type($atch);
$tmp = str_replace('\\','/', $atch);
$file_name = basename($tmp);
$m->addAttachmentFromFile($file_name, $atch, $mime_type);
$response = $ses->sendEmail($m,false,true);
$m->clearRecipients();
$m->attachments = [];
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
Solved
Just added $ses->setBulkMode(true); after $ses->enableVerifyPeer(false);. ..:)

PHP: SendGrid mail attachments from S3 server

I need to be able to send one, maybe more, files stored on an Amazon S3 server as attachments in an email created using SendGrid.
The problem I have is that I'm not a web dev expert and the sparse PHP examples I can find are not helping me much.
Do I need to download the files from the S3 server to the local /tmp directory and add them as attachments that way, or can I pass the body of the file from the FileController and insert it as an attachment that way?
I'm not really sure where to start, but here's what I've done so far:
$attachments = array();
// Process the attachment_ids
foreach($attachment_ids as $attachment_id) {
// Get the file if it is attached to the Activity
if (in_array($attachment_id, $activity_file_ids)) {
$file = File::find($attachment_id);
$fileController = new FileController($this->_app);
$fileObject = $fileController->getFile($attachment_id);
error_log(print_r($fileObject, true));
$attachment = array();
$attachment['content'] = $fileObject;
$attachment['type'] = $fileController->mime_content_type($file->file_ext);
$attachment['name'] = explode(".", $file->filename, 2)[0];
$attachment['filename'] = $file->filename;
$attachment['disposition'] = "inline";
$attachment['content_id'] = '';
}
}
My next step would be to push the $attachment array to the $attachments array. Once $attachments is complete, iterate through it and add each $attachment to the SendGrid e-mail object (the e-mail is working fine without attachments, btw.)
Problem is, I'm not sure I'm going down the right road with this or if there's a much shorter and neater (and working) way of doing it?
FileController->getFile() essentially does this:
$file = $this->_s3->getObject(array(
'Bucket' => $bucket,
'Key' => $filename,
));
return $file['Body'];
Any help (especially code examples) would be greatly appreciated!
Okay, I've got a working solution to this now - here's the code:
// Process the attachment_ids
foreach($attachment_ids as $attachment_id) {
// Get the file if it is attached to the Activity
if (in_array($attachment_id, $activity_file_ids)) {
// Get the file record
$file = File::find($attachment_id);
// Get an instance of FileController
$fileController = new FileController($this->_app);
// Set up the Attachment object
$attachment = new \SendGrid\Attachment();
$attachment->setContent(base64_encode($fileController->getFile($attachment_id)));
$attachment->setType($fileController->mime_content_type($file->file_ext));
$attachment->setFilename($file->filename);
$attachment->setDisposition("attachment");
$attachment->setContentId($file->file_desc);
// Add the attachment to the mail
$mail->addAttachment($attachment);
}
}
Don't know if it will help anybody else, but there it is. The solution was to get the file from the S3 server and pass base64_encode($file['Body']) to the setContent function of an instantiated Attachment object, along with setting a few other fields for it too.

azure image blob is prompting download option

okay i someone find out how to upload blobs in container of using php on azure, but when even i view the image with plain url like https://my.blob.url.net/my_image_folder/my_image_name.jpg the browser prompts to download the image, instead of viewing the image, like normal image is viewed on browser, here is the code i'm using while uploading
<?php
require_once __DIR__.'/vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
$connectionString = 'DefaultEndpointsProtocol=http;AccountName=account_name;AccountKey=my_key_value';
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$content = fopen('folder/image.jpg','r');
$blob_name = 'image_name.jpg';
try
{
$blobRestProxy->createBlockBlob("container_name", $blob_name, $content);
}
catch(ServiceException $e)
{
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
this code is working fine, but when accessing the url, it prompts download option, which means i cannot use for img html tag
You have to set the blob's content type to an appropriate mime type. The following is a snippet in C# that shows how this can be done:
entryData.DestinationBlob.Properties.ContentType = "image/jpeg";
entryData.DestinationBlob.SetProperties();
We need to set its property Content type through Blob Options class.
PHP :
namespace - use MicrosoftAzure\Storage\Blob\Models\CreateBlobOptions;
//use code where you are creating blob
$opts = new CreateBlobOptions();
//$opts->setCacheControl('test');
$opts->setContentEncoding('UTF-8');
$opts->setContentLanguage('en-us');
//$opts->setContentLength(512);
$opts->setContentMD5(null);
$opts->setContentType($mimeType);
$blobRestProxy->createBlockBlob($containerName, $indexFile, $content,$opts);
$mimeType is Type of your file text/html, text/pdf. It will work in git.
package : "microsoft/windowsazure": "^0.5"

How to use $_FILES to store a BLOB Windows Azure

I am using windows azure blob storage service to store data. My php file is this
<?php
require_once __DIR__ . '/vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Blob\Models\CreateContainerOptions;
use WindowsAzure\Blob\Models\PublicAccessType;
use WindowsAzure\Common\ServiceException;
// Create blob REST proxy.
$connectionString = "[CONNECTION STRING (WORKS)]";
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
$blob_name = "myblob";
// Create blob REST proxy.
try {
//Upload blob
$blobRestProxy->createBlockBlob("containerName",$blob_name, $_FILES['userfile']['tmp_name']);
echo '104';
}
catch(ServiceException $e){
// Handle exception based on error codes and messages.
// Error codes and messages are here:
// http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
?>
The BLOB is created perfectly...
The only problem i'm having is when I use $_FILES['userfile']['tmp_name'] it actually stores in the BLOB the PATH of the file, not the contents of the file itself.
My question is, how can I store a BLOB using the $_FILES contents?
You need to read the contents of the file using file_get_contents() or other method:
$blob_content = file_get_contents($_FILES['userfile']['tmp_name']);
$blobRestProxy->createBlockBlob("containerName", $blob_name, $blob_content);
MS actually attempts to give an example here, however fopen() doesn't work like that.

azure: Set blob content type using PHP

How do I use the setBlobProperties in php to set the ContentType? The code below is what I found via google, but that one isn't working. The video does appear in the blob storage, but the content-type is set to: application/octet-stream. Also the language isn't set to 'nl-BE' but shows 'empty'.
$storageClient->putLargeBlob($_POST['container'], $_POST['filename'], $tempFile);
$storageClient->setBlobProperties($_POST['container'], $_POST['filename'], null, array(
'x-ms-blob-content-language' => 'nl-BE',
'x-ms-blob-content-type' => 'video/mp4'
));
Ok, excuse me.. this code does work, but I was referring to the wrong one (had two php pages with the same name, and was editing in the one that i'm not using).
Sorry! But now, someone who is looking for this in the future, will have this as the answer :).
Using new sdk, one can set the content type as follows(i have set the content type for gif image in this example).
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
//upload
$blob_name = "image.gif";
$content = fopen("image.gif", "r");
$options = new CreateBlobOptions();
$options->setBlobContentType("image/gif");
try {
//Upload blob
$blobRestProxy->createBlockBlob("containername", $blob_name, $content, $options);
echo "success";
} catch(ServiceException $e){
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}

Categories