Mandrill email attachments file path - php

I am trying to add some attachments to an email that is being sent using the mandrill api via a php wrapper. I have tried a number of different things to try to successfully attach the file but to no avail.
I am using cakephp 2.x but I don't think that has any particular significance in this instance (maybe it does?!).
I am using the php wrapper maintained by mandrill at https://bitbucket.org/mailchimp/mandrill-api-php
Here is the code:
$mandrill = new Mandrill(Configure::read('Site.mandrill_key'));
$params = array(
'html' => '
<p>Hi '.$user['User']['name'].',</p>
<p>tIt is that time of the year again.<br />
Please login to the website members area and upload your renewal requirements.</p>
<p>Kind regards.</p>',
"text" => null,
"from_email" => Configure::read('Site.email'),
"from_name" => Configure::read('Site.title'),
"subject" => "Renewal Pending",
"to" => array(array('email' => $user['User']['email'])),
"track_opens" => true,
"track_clicks" => true,
"auto_text" => true,
"attachments" => array(
array(
'path' => WWW_ROOT.'files/downloads/renewals',
'type' => "application/pdf",
'name' => 'document.pdf',
)
)
);
$mandrill->messages->send($params, true);
}
This shows that an attachment has been added to the email and is a pdf but the actual pdf has not been attached.
I also tried by adding the path directly onto the file as in:
"attachments" => array(
array(
'type' => "application/pdf",
'name' => WWW_ROOT.'files/downloads/renewals/document.pdf',
)
I have googled and read every article I can find but cannot find any specific reference as to how I should specify the path for mandrill to correctly attach my attachment.
Any help will be greatly appreciated.

OK. So thanks to Kaitlin for her input.
The PHP way to deal with this is to get the file and then base64_encode it:
$attachment = file_get_contents(WWW_ROOT.'files/downloads/file.pdf');
$attachment_encoded = base64_encode($attachment);
and then in the attachments part of the mandrill array you pass the :
"attachments" => array(
array(
'content' => $attachment_encoded,
'type' => "application/pdf",
'name' => 'file.pdf',
)
So easy! Thanks again Kaitlin!

It looks like you're passing a parameter called path, but the Mandrill API doesn't take the path of a file for attachments. If you're using the send or send-template call, attachments should be an associative array (hash) with three keys: type, name, and content.
The content parameter should be the contents of the file as a Base64 encoded string, so instead of path, you'll want to get the file contents, Base64 encode them, and then pass them in a parameter called content instead of path.
You can see the full details of the parameters, including for attachments, in the Mandrill API docs here: https://mandrillapp.com/api/docs/messages.html#method=send

Related

How do I merge the temp file and file name together after the file has been uploaded?

I am using PHP to collect documents from users. I have a simple HTML form that allows users to upload documents. Once the document has been uploaded, I send myself an e-mail containing the document the user uploaded as an attached file.
My problem is, when I use $_FILES["resume"]["tmp_name"], the file is sent but it is in the wrong format and does not preserve the original file name. When I try sending the file with $_FILES["resume"]["name"], the document isn’t sent.
How do I send an e-mail containing the file immediately it is uploaded, in the right format and with the right name?
Update, here is my current code (I am using Mailgun to send the email):
` $mgClient = new Mailgun('key-xxxxx');
$domain = "mg.xxxxx.com";
$result = $mgClient->sendMessage($domain, array(
'from' => $postdata['fullname'].' <'.$postdata['email'].'>',
'to' => 'xxxx#gmail.com',
'subject' => $postdata['fullname'].' has sent you a resumé',
'text' => 'This is a resumé from '.$postdata['fullname'].'
applying to be part of the xxxx team. His/her resumé is attached to
this email.'
), array(
'attachment' => array(''.$_FILES["resume"]["tmp_name"].'')`
Assuming you're using the official mailgun-php SDK, you can set the file's name into the attachment array:
$mgClient = new Mailgun('key-xxxxx');
$domain = "mg.xxxxx.com";
$result = $mgClient->sendMessage($domain, array(/* ... */), array(
'attachment' => array(
// array entry for each file:
array(
// filePath: path to the actual file
'filePath' => $_FILES["resume"]["tmp_name"],
// remoteName: user-visible attachment name
'remoteName' => $_FILES["resume"]["name"]
)
)
));

Mailchimp create campaign with DrewM PHP wrapper

How do I create a campaign using this wrapper and pass parameters? Ive searched the internet and the documentation but their isn't enough information or example code
$mc->post('campaigns');
just returns an error. Thanks in advance.
Assuming you've authenticated, etc., you can just add in your parameters like the Mailchimp docs show:
$result = $MailChimp->post("campaigns", [
'type' => 'regular',
'recipients' => ['list_id' => 'xxx'],
'settings' => ['subject_line' => 'Your Purchase Receipt',
'reply_to' => 'orders#example.com',
'from_name' => 'Customer Service']
]);
The wrapper doesn't really do anything; it just provides a standard way to pass these arrays to Mailchimp.

Inline multiple images Mailgun API Batch

I am trying to pass multiple images via Mailgun's inline API-parameter. I have no problem with only one image, but when I try with multiple images - as in the code below - only the last image in the array is displayed in the email.
$template = View::make('emails.template')->render();
$result = $mgClient->sendMessage($domain, array(
'from' => $sender,
'to' => implode(',',$emailAddresses),
'subject' => '%recipient.subject%',
'text' => $messageText,
'recipient-variables' => json_encode($credentials),
'html' => $template
), array(
'inline' => array(
'path/to/image1.png',
'path/to/image2.png',
'path/to/image3.png',
'path/to/image4.png')
));
The code above works as if the last element in the array is the only element.
The documentation for sending inline images with Mailgun is found here and it's said here that "You can post multiple inline values" which means that I'm definitely doing something wrong.
Try this once:
$result = $mgClient->sendMessage($domain, array(
'from' => $sender,
'to' => implode(',',$emailAddresses),
'subject' => '%recipient.subject%',
'text' => $messageText,
'recipient-variables' => json_encode($credentials),
'html' => $template
), array(
'inline' => array(
array('path/to/image1.png'),
array('path/to/image2.png'),
array('path/to/image3.png'),
array('path/to/image4.png')
)));
Basically wrapping each image path in an array.
Also what is the contents of $template?
This was actually a recently introduced bug. A new pull request has been submitted to the official Mailgun PHP SDK, for more info see here.
So to answer the question: the code is working fine, as soon as the SDK is updated according to above pull request. For now I edited my local copy of mailgun-php accordingly and it worked fine. Many thanks to Travis Swientek on Mailgun for quick response.

How to send image using Mandrill but image name should not rename?

Image file attachments in mandrill api working fine. But here,
'type' => 'image/jpeg',
'name' => "", // Here I didn't know what I am use
'content' => base64_encode(file_get_contents($img))
You can do something like
'name' => basename($img)
if you do not want to rename the image.
Hope this helps,

File upload in module configuration panel, Prestashop

I'm trying to create a XML import module that will convert given file to CSV format and then use that CSV to import categories and products.
I have a working configuration page made with getContent() it basically calls a method that generates this form via $helper->generateForm(). $helper is a HelperForm() object.
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'file',
'label' => $this->l('XML file'),
'name' => 'XMLIMPORT_XML_FILE',
'desc' => $this->l('Select file you wish to import.'),
'required' => true
),
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Enter a valid email address'),
'name' => 'XMLIMPORT_LINES',
'label' => $this->l('Records per file'),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
I need to get this data to my XML converter. How do I upload a file (around 10-20MB) to Prestashop to be then able to do other stuff with it? How to save it permanently on the server?
I tried doing this:
return array(
'XMLIMPORT_XML_FILE' => Configuration::get('XMLIMPORT_XML_FILE', null),
'XMLIMPORT_LINES' => Configuration::get('XMLIMPORT_LINES', 1000)
);
And after that this:
$form_values = $this->getConfigFormValues(); // returned array from above
foreach (array_keys($form_values) as $key)
Configuration::updateValue($key, Tools::getValue($key));
And later using my own class for XML conversion like this, hoping that it will give me file handle.
$xml_converter = new XMLToCSVConverter(Configuration::get('XMLIMPORT_XML_FILE'), 'output', 'example_products.php');
Apparently it didn't as nothing happens. The class itself is working fine outside of Prestashop module. The constructor is __construct($xml_file, $csv_filename, $template_file).
I need to pass the file I upload to that constructor. I've been struggling for days now.
#edit: I can see the contents of the file inside the HTTP call when submit is clicked. But how do I pass that file to my class?
As far as I remember 'type' => 'file', doesn't actually save any values in the database. This type is only meant to output a file field in your form.
After submitting, you should then do you custom processing with $_FILES['XMLIMPORT_XML_FILE'] : move to upload/ or whereever you want.
'XMLIMPORT_XML_FILE' => Configuration::get('XMLIMPORT_XML_FILE', null), won't return you anything. After uploading you my wish to save the uploaded file path here, but it won't show up next time in the form unless you build the output yourself.
Module configratuon is meant to save text config values. Handling files is trickier and you have to do them yourself each time.
EDIT:
To intercept the saving process, look up the submit button name and make an if statement:
public function getContent() {
if(Tools::isSubmit('submitButtonName')) {
error_log(print_r($_FILES, 1));
}
}
There's probably a function postProcess which does the same (it looks like you copied the methods from a default module).
prestashop handles the image upload with ImageManager class, this class contains more methods which are useful for handling image upload, resize etc.. so its better refer the default homeslider module for the image upload using a module. This module is handling the image upload process in postProcess method with the help of ImageManager class, this class methods will do the all the processes related to upload.

Categories