I try to send attachment pdf file. I get the email but no attachmetn.
I have try to use https://github.com/sendinblue/APIv3-php-library/blob/master/docs/Model/SendSmtpEmail.mdenter
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['to'] = array(array('email'=>'email#email.com'));
$sendSmtpEmail['templateId'] = 39;
$sendSmtpEmail['params'] = array(
'NUMEROFACTURE'=> "12345",
'CODECLIENT' => "1234567",
'TOSEND' => "email1#email.net",
'MONTANTFACTURE'=> number_format(12, 2, ',', ' '),
);
$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['url']= __DIR__'/facture/Facture-'.$row["ClePiece"].'.pdf';
$attachement['name']= 'Facture-'.$row["ClePiece"].'.pdf';
$attachement['content']= "utf-8";
$sendSmtpEmail['attachment']= $attachement;
$sendSmtpEmail['headers'] = array('Content-Type'=>'application/pdf','Content-Disposition'=>'attachment','filename'=>'Facture-'.$row["ClePiece"].'.pdf',"charset"=>"utf-8");
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
According to the SendSmtpEmailAttachment documentation, you have two ways to attach a file using a url or a content.
url | Absolute url of the attachment (no local file).
content | Base64 encoded chunk data of the attachment generated on the fly
You are wrongly assigning "utf-8" to the content. This mean you need to convert the pdf data into a base64 chunk data. First, get the pdf path in your server as $pdfdocPath. Get the pdf content using file_get_contents method and encode it using base64_encode method. Finally, split the content in small chunks using chunk_split as shown in the next snippet:
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['to'] = array(array('email'=>'email#email.com'));
$sendSmtpEmail['templateId'] = 39;
$sendSmtpEmail['params'] = array(
'NUMEROFACTURE'=> "12345",
'CODECLIENT' => "1234567",
'TOSEND' => "email1#email.net",
'MONTANTFACTURE'=> number_format(12, 2, ',', ' '),
);
$pdfdocPath = __DIR__.'/facture/Facture-'.$row["ClePiece"].'.pdf';
$b64Doc = chunk_split(base64_encode(file_get_contents($pdfdocPath)));
$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['name']= 'Facture-'.$row["ClePiece"].'.pdf';
$attachement['content']= $b64Doc;
$sendSmtpEmail['attachment']= $attachement;
$sendSmtpEmail['headers'] = array('Content-Type'=>'application/pdf','Content-Disposition'=>'attachment','filename'=>'Facture-'.$row["ClePiece"].'.pdf',"charset"=>"utf-8");
Update:
I checked the APIv3-php-library source code and I found that the constructor will do the validation of name and content.
$dataEmail = new \SendinBlue\Client\Model\SendEmail();
$dataEmail['emailTo'] = ['abc#example.com', 'asd#example.com'];
// PDF wrapper
$pdfDocPath = __DIR__.'/facture/Facture-'.$row["ClePiece"].'.pdf';
$content = chunk_split(base64_encode(file_get_contents($pdfDocPath)));
// Ends pdf wrapper
$attachment_item = array(
'name'=>'Facture-'.$row["ClePiece"].'.pdf',
'content'=>$content
);
$attachment_list = array($attachment_item);
// Ends pdf wrapper
$dataEmail['attachment'] = $attachment_list;
$templateId = 39;
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTemplate($templateId, $dataEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
$dataEmail= new \SendinBlue\Client\Model\SendEmail();
$dataEmail['emailTo'] = ['abc#example.com', 'asd#example.com'];
$dataEmail['attachmentUrl'] = "http://www.ac-grenoble.fr/ia07/spip/IMG/pdf/tutoriel_pdf_creator-2.pdf";
// if you want to use content attachment base64
// $b64Doc = chunk_split(base64_encode($data));
// $attachment_array = array(array(
// 'content'=>$b64Doc,
// 'name'=>'Facture-'.$row["ClePiece"].'.pdf'
// ));
// $dataEmail['attachment'] = $attachment_array;
//Don't forget to delete attachmentUrl
$templateId = 39;
$dataEmail = $dataEmail;
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTemplate($templateId, $dataEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
According to the documentaiton SMTPApi->sendTransacEmail function gets SendSmtpEmail object. That object has restrictions for the attachment attribute:
If templateId is passed and is in New Template Language format then only attachment url is accepted. If template is in Old template Language format, then attachment is ignored.
But SMTPApi->sendTemplate function don't have this restriction.
$credentials = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR-KEY');
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(new GuzzleHttp\Client(),$credentials);
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail([
'subject' => 'test email!',
'sender' => ['name' => 'from name', 'email' => 'from#mail.com'],
//'replyTo' => ['name' => 'test', 'email' => 'noreply#example.com'],
'to' => [[ 'name' => 'Tushar Aher', 'email' => 'receivedto#gmail.com']],
'htmlContent' => '<html><body><h1>This is a transactional email {{params.bodyMessage}}</h1></body></html>',
'params' => ['bodyMessage' => 'this is a test!']
]);
/*$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['url']= FCPATH.'uploads/invoice/ticket-498410.pdf';
$attachement['name']= 'ticket-498410.pdf';
$attachement['content']= "utf-8";
$sendSmtpEmail['attachment']= $attachement;*/
// PDF wrapper
$pdfDocPath = FCPATH.'uploads/invoice/ticket-498410.pdf';
$content = chunk_split(base64_encode(file_get_contents($pdfDocPath)));
// Ends pdf wrapper
$attachment_item = array(
'name'=>'ticket-498410.pdf',
'content'=>$content
);
$attachment_list = array($attachment_item);
// Ends pdf wrapper
$sendSmtpEmail['attachment'] = $attachment_list;
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
print_r($result);
} catch (Exception $e) {
echo $e->getMessage(),PHP_EOL;
}
Related
Using Sendinblue API, I get a Bad Request response: {"code":"invalid_parameter","message":"Invalid emails format"}when I'm trying to use the functionAddContactToList`.
I have no problem when trying to create contact. Contact is sent with emails and attributes. I want now to add existing contacts in a list.
This is the code of the add contact to list page:
// Configure API key authorization: api-key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'xxxxxxxxxxxxxxxxxx');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api-key', 'Bearer');
// Configure API key authorization: partner-key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('partner-key', 'xxxxxxxxxxxxxxxxxxxxxxx');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('partner-key', 'Bearer');
$apiInstance = new SendinBlue\Client\Api\ContactsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$row = 0;
if (($handle = fopen("contactlist.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ";")) !== FALSE) {
$row++;
usleep(1000);
if($row>70){
$listId = 42; // int | Id of the list
$contactEmails = new \SendinBlue\Client\Model\AddContactToList(); // \SendinBlue\Client\Model\AddContactToList | Emails addresses of the contacts
$contactEmails['emails'] =$data[1];
echo $data[1];echo '<br>';
try {
$result = $apiInstance->addContactToList($listId, $contactEmails);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ContactsApi->addContactToList: ', $e->getMessage(), PHP_EOL;
}
echo '<br>';echo '<br>';echo '<br>';
}
if($row==400){
die();
}
}
fclose($handle);
}
?>
This is the result I get:
xxxxx#example.com
Exception when calling ContactsApi->addContactToList:
[400] Client error: POST
https://api.sendinblue.com/v3/contacts/lists/42/contacts/add resulted
in a 400 Bad Request response:
{"code":"invalid_parameter","message":"Invalid emails format"}
Thank you for your help.
Here is my working code :
require_once(__DIR__ . '/vendor/autoload.php');
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR-APIKEY');
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('partner-key', 'YOUR-APIKEY');
$apiInstance = new SendinBlue\Client\Api\ContactsApi(
new GuzzleHttp\Client(),
$config
);
$createAttribute = new \SendinBlue\Client\Model\CreateAttribute([
'name' => 'Your Name',
'type' => 'email' // email, sms
]);
$createContact = new \SendinBlue\Client\Model\CreateContact([
'email' => 'test#email.be',
'attributes' => $createAttribute,
'listIds' => [28], // Int() | Number of your list in your account
]); // \SendinBlue\Client\Model\CreateContact | Values to create a contact
try {
$result = $apiInstance->createContact($createContact);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ContactsApi->createContact: ', $e->getMessage(), PHP_EOL;
}
So, I'm novice at best with php, but I've figured out how to set up and send transactional emails with sendinblue.
But for whatever reason, I can't seem to set the attributes.
This is really the only line of the code that I can't seem to get to work.
$sendEmail['attributes'] = array('FIRSTNAME' => "STEVE");$sendEmail['attributes'] = array('FIRSTNAME' => "STEVE");
I've also tried
$sendEmail['params'] = array('FIRSTNAME' => "STEVE");
and
$params['attributes'] = array('FIRSTNAME' => "STEVE");
...and probably 127 variations of the above, but I can't seem to get it it to work.
I also can't seem to figure out how to create a contact with php...
What is the "create contact" equivilent of this line of code:
$sendEmail = new \SendinBlue\Client\Model\SendEmail();
?
Like I said, my emails asre sending, but where I expect them to read "Dear STEVE," they read "Dear ,"
BELOW IS THE FULL CODE:
<?php
# Include the SendinBlue library\
require_once('../vendor/autoload.php');
# Instantiate the client\
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'MY API KEY HERE');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api-key', 'Bearer');
// Configure API key authorization: partner-key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('partner-key', 'MY API KEY HERE');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('partner-key', 'Bearer');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$templateId = 2; // int | Id of the template
$sendEmail = new \SendinBlue\Client\Model\SendEmail(); // \SendinBlue\Client\Model\SendEmail |
$sendEmail['emailTo'] = array("test#example.com");
$params['attributes'] = array('FIRSTNAME' => "STEVE"); //THIS IS THE LINE OF CODE THAT ISN'T WORKING.
//$mail->setFrom('info#myeasy.wedding', 'My Easy Wedding');
try {
$result = $apiInstance->sendTemplate($templateId, $sendEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
?>
You need to use sendTransacEmail() and it works with PARAM. Need to add code in template {{ params.FIRSTNAME }}
Complete API code
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'MY API KEY HERE');
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$sendEmail = new SendinBlue\Client\Model\SendSmtpEmail();
$sendEmail['to'] = [["email" => 'test#example.com', "name" => 'test']];
$sendEmail['templateId'] = 2;
$sendEmail['params'] = ['FIRSTNAME' => 'Test'];
try {
$response = $apiInstance->sendTransacEmail($sendEmail);
print_r($response);
} catch (Exception $e) {
echo 'Exception when calling AccountApi->getAccount: ', $e->getMessage(), PHP_EOL;
}
try to use FNAME instead of FIRSTNAME
Reference
<?php
require_once(__DIR__ . '/vendor/autoload.php');
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR API KEY');
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
new GuzzleHttp\Client(),
$config
);
$templateId = 1;
$sendEmail = new \SendinBlue\Client\Model\SendEmail()
$sendEmail['emailTo'] = array('example#example.com');
$sendEmail['emailCc'] = array('example1#example1.com');
$sendEmail['headers'] = array('Some-Custom-Name' => 'unique-id-1234');
$sendEmail['attributes'] = array('FNAME' => 'Jane', 'LNAME' => 'Doe');
$sendEmail['replyTo'] = 'replyto#domain.com';
$sendEmail['attachmentUrl'] = 'https://example.net/upload-file.pdf';
try {
$result = $apiInstance->sendTemplate($templateId, $sendEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling TransactionalEmailsApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
?>
You can find more examples at https://developers.sendinblue.com/
I want to see XML data that is being POSTed via email.
The process:
1) XML POST is made to a PHP script.
2) The PHP script simply mails me the $_POST data via print_r($_POST, true) as the message.
I am using PHPMailer and SimpleXML to accomplish this.
Here is my code which POSTs the XML:
$xml = new SimpleXMLElement('<lead/>');
$post_body = array_flip($template['post_body']);
array_walk_recursive($post_body, array($xml, 'addChild'));
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/xml\r\n",
'content' => $xml->asXML(),
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents($template['address'], null, $context);
$post_body is an array which looks like this:
Array
(
[testbuyer] => buyerName
[tdunn5e#hatena.ne.jp] => testEmail
[Timothy] => leadFirstName
[world] => customTest2
)
Here is my code which sends the email:
try
{
$mailer = new PHPMailer();
$mailer->isSMTP();
$mailer->Host = EMAIL_HOST;
$mailer->Port = EMAIL_PORT;
$mailer->SMTPAuth = true;
$mailer->Username = EMAIL_USERNAME;
$mailer->Password = EMAIL_PASSWORD;
$mailer->setFrom(EMAIL_ADDRESS);
$mailer->addAddress('myemail#gmail.com');
$mailer->Subject = 'Test POST';
$mailer->Body = print_r($_POST, true);
$mailer->send();
$response = 'Mail sent OK';
}
catch (phpmailerException $e)
{
$response = $e->errorMessage();
}
catch (Exception $e)
{
$response = $e->getMessage();
}
I receive the email fine, but the message just shows an empty array. It looks like this:
Array
(
)
Why is this happening? I just want to see the XML in the message so I can verify its all working properly. Any help would be appreciated.
I'm trying to update the content of the file. Use the PHP function:
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$additionalParams = array(
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
....
$data = retrieveAllFiles($service);
$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);
$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
In additionalParams need to add :
'uploadType' => 'multipart',
or
'uploadType' => 'media',
Hope it helps!
How to apply word wrap using zend_pdf library, I am using MyPDFTable lib as an extension for zendPdf lib.
I have used following code.
<?php
// include auto-loader class
require_once 'Zend/Loader/Autoloader.php';
// register auto-loader
$loader = Zend_Loader_Autoloader::getInstance();
try {
// set up database access parameters
$params = array ('host' => '127.0.0.1',
'username' => 'user',
'password' => 'pass',
'dbname' => 'world');
// configure adapter and query database
$db = Zend_Db::factory('PDO_MYSQL', $params);
$stmt = $db->query('SELECT Name, Code, Region FROM country LIMIT 0, 150');
// create PDF
$pdf = new My_Pdf_Document('example.pdf', '.');
// create page
$page = $pdf->createPage();
// define font resource
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
// set font
$page->setFont($font, 24);
// create table
$table = new My_Pdf_Table(3);
// iterate over record set
// set up table content
while ($record = $stmt->fetch()) {
$row = new My_Pdf_Table_Row();
$cols = array();
foreach ($record as $k => $v) {
$col = new My_Pdf_Table_Column();
$col->setText($v);
$cols[] = $col;
}
$row->setColumns($cols);
$row->setFont($font, 14);
$row->setBorder(My_Pdf::TOP, new Zend_Pdf_Style());
$row->setBorder(My_Pdf::BOTTOM, new Zend_Pdf_Style());
$row->setBorder(My_Pdf::LEFT, new Zend_Pdf_Style());
$row->setCellPaddings(array(10,10,10,10));
$table->addRow($row);
}
// add table to page
$page->addTable($table, 0, 0);
// add page to document
$pdf->addPage($page);
// save as file
$pdf->save();
echo 'SUCCESS: Document saved!';
} catch (Zend_Pdf_Exception $e) {
die ('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
die ('Application error: ' . $e->getMessage());
}
?>
You will find this code on http://devzone.zend.com/1776/creating-pdf-documents-with-zend-framework/ In topic "Turning The Tables".
This tutorial talks about the same problem you faced. They have provided a custom solution also!
http://www.ibm.com/developerworks/opensource/tutorials/os-php-zend5/section4.html