I want to send an email to multiple email addresses using one Mandrill API call, here is what we do to send to only one email:
<?php
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to only one email address:
'to' => array(
array(
'email' => $the_email,
)
),
// ...blah blah, doesn't matter
);
?>
This is OK but while we want to send the message to multiple email addresses, we must have this:
<?php
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to more than one email:
'to' => array(
array(
'email' => $email_1,
),
array(
'email' => $email_2,
),
array(
'email' => $email_3,
),
),
// ...blah blah, doesn't matter
);
?>
As you can see, we've repeated the array part, now assuming we have this array:
$subscribers_email = array(
'email_1#xxx.com',
'email_2#xxx.com',
'email_3#xxx.com'
);
How could we possibly make the mandrill code to use $subscribers_email? Of course we can write the email addresses in the mandrill code like:
<?php
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to only one amil address:
'to' => array(
array(
'email' => 'email_1#xxx.com',
),
array(
'email' => 'email_2#xxx.com',
),
array(
'email' => 'email_3#xxx.com',
),
),
// ...blah blah, doesn't matter
);
?>
But that's not what I want, imagine we need to make this dynamic and as a function, like:
function sendEmailToArray($subscribers_email){
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to only one amil address:
'to' => array(
$subscribers_email
),
// ...blah blah, doesn't matter
);
}
So I want to make that array in a dynamic way, is that possible?
You should convert your array as your requirement.
Use this code
function sendEmailToArray($subscribers_email){
//$subscribers_email = array(
// 'email_1#xxx.com',
// 'email_2#xxx.com',
// 'email_3#xxx.com'
//);
$final_subscribers_email = array();
foreach ($subscribers_email as $key => $value) {
array_push($final_subscribers_email, array("email" => $value));
}
$mandrill_message = array(
// ...blah blah, doesn't matter
// To send to only one email address:
'to' => $final_subscribers_email,
// ...blah blah, doesn't matter
);
}
You can use array_walk for this.
$subscribers_email = array(
'email_1#xxx.com',
'email_2#xxx.com',
'email_3#xxx.com'
);
sendEmailToArray($subscribers_email);
function sendEmailToArray($subscribers_email){
// Convert the array
array_walk($subscribers_email, function(&$input){
$input = array('email' => $input);
});
// Send the emails
$mandrill_message = array(
'to' => array($subscribers_email),
);
}
Related
I am trying to send emails to multiple recipients using SendinBlue's API v3 Php Library (https://github.com/sendinblue/APIv3-php-library).
The following code, I think, it set up correctly - in that the code goes down printing the $result part of the code, meaning there was no exception.
However, when testing sending to multiple recipients, only the email address that's the last one in the array (person2#exampe.com in the code below) receives the email.
If I flip the to array contents around, so that person1#example.com appears last in the array, then only that address receives the email.
This is the sample code:
// ####################################################
// Sendinblue Email
// ####################################################
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', $send_in_blue_api_key);
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(
new GuzzleHttp\Client(),
$config
);
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['subject'] = 'Mulitple Recipients Email Test';
$sendSmtpEmail['htmlContent'] = $html;
$sendSmtpEmail['sender'] = array('name' => 'Test Messages', 'email' => 'messages#example.com');
$sendSmtpEmail['to'] = array(
array('email' => 'person1#example.com', 'name' => 'Bugs Bunny'
, 'email' => 'person2#example.com', 'name' => 'Daffy Duck')
);
$sendSmtpEmail['replyTo'] = array('email' => 'sender#example.com', 'name' => 'Reply Name');
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
print_r($result);
} catch (Exception $e) {
$send_error = $e->getMessage();
print_r($send_error);
}
I tried changing the to array from:
$sendSmtpEmail['to'] = array(
array('email' => 'person1#example.com', 'name' => 'Bugs Bunny'
, 'email' => 'person2#example.com', 'name' => 'Daffy Duck')
);
To:
$sendSmtpEmail['to'] = array('email' => 'person1#example.com', 'name' => 'Bugs Bunny'
, 'email' => 'person2#example.com', 'name' => 'Daffy Duck');
But, the API returns this, which I think means the way I'm defining the multiple recipients in the to array is correct:
[400] Client error: `POST https://api.sendinblue.com/v3/smtp/email` resulted in a `400 Bad Request` response:
{"code":"invalid_parameter","message":"to is not valid"}
I wondered if there is any way around this issue?
You have to make an array of arrays. Each array should have email and name key:
Short array syntax:
$sendSmtpEmail['to'] = [
['email' => 'person1#example.com', 'name' => 'Bugs Bunny'],
['email' => 'person2#example.com', 'name' => 'Daffy Duck'],
];
Equivalent to:
$sendSmtpEmail['to'] = array(
array('email' => 'person1#example.com', 'name' => 'Bugs Bunny'),
array('email' => 'person2#example.com', 'name' => 'Daffy Duck'),
);
I have successfully setup a Mailgun account for Transaction email.
The Problem;
I want my email content which are dynamic inside my Email Template please help and even my file attachment not working
<?php
$filePath='#/home/allinclende/public_html/apply/CIW.pdf';
$message = $message;
$html = file_get_contents('email_1.html');
$html .= $message;
$mgClient = new Mailgun('key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
//enter domain which you find in Default Password
$domain = "apply.allinc.com";
# Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
'from' => 'Jane Doe <jdoe#allinc.com>',
'to' => $add,
'cc' => 'inquiry <info#allinc.com>',
'subject' => $subject,
'text' => $message,
'html' => $html,
'attachment[1]' => $filePath
));
?>
In your email_1.html file include some unique placeholders. Make an array containing them:
$search = array("FIRSTNAME", "LASTNAME", "APPOINTMENTDATE");
Query your database and get the variables to replace each one, make an array of those:
$replace = array($firstname, $lastname, $appointmentdate);
Then it's as simple as:
$customhtml = str_replace($search, $replace, $html);
Send $customhtml via mailgun, then loop through again to personalise the email for each customer
Correct construct for sending an attachment is like this:
$result = $mgClient->sendMessage($domain, array(
'from' => 'Jane Doe <jdoe#allinc.com>',
'to' => $add,
'cc' => 'inquiry <info#allinc.com>',
'subject' => $subject,
'text' => $message,
'html' => $html
), array(
'attachment' => array('#/home/allinclende/public_html/apply/CIW.pdf')
));
I want to be able to send an automated email to all my users with the top 5 projects of my application. I wanna do this with a cron job on my server.
I have constructed my function in my Marketing class. I created an artisan command but I just have no idea if my method will work. I have no idea how I can get the data in my variables to send in the mail.
I am not sure if my variable $name, $email, $projects will work in the mail and if the mail will actually be sent every month. I just don't think this code will work. And I don't have time to wait a month to test it out :p
My SendNewslettterCommand:
public function handle()
{
foreach(User::all() as $user)
{
$name = $user->name;
$email = $user->email;
$projects = "a query to find top 5 projects of the week";
$Marketing = new Marketing;
$Marketing->sendNewsletter($name, $email, $projects);
}
}
My sendNewsletter function in my Marketing class:
public function sendNewsletter($name, $email, $projects)
{
// In template content you write your dynamic content if you use <mc:edit> tags.
$template_content = [];
$message = array(
'subject' => 'SP*RK - TOP 5 projecten van de maand!',
'from_email' => 'noreply#spark.com',
'from_name' => 'SP*RK',
'to' => array(
array(
'email' => $email,
'name' => $name,
'type' => 'to'
)
),
'merge_vars' => array(
array(
'rcpt' => $email,
'vars' => array(
array(
'name' => 'NAME',
'content' => $name
),
array(
'name' => 'PROJECTS',
'content' => $projects
)
)
)
)
);
MandrillMail::messages()->sendTemplate('newsletter', $template_content, $message);
}
If this is all correct my next steps would be to register my command in artisan by editing app/start/artisan.php and adding:
Artisan::add(new SendNewsletterCommand);
After this I should my command to my crontab
Is this correct or not?
I am working on a campaign monitor api which creates a custom list with custom fields.
When I try and add subscribers it used to work, now when I look at the list its not added them. Although its still returning a success code 201.
function addSubscriber($list_id, $emailAddress, $name, $title, $showName, $showDate, $showTime){
//create subscriber
$subscriber = array(
'EmailAddress' => $emailAddress,
'Name' => $name,
'CustomFields' => array(
array(
'Key' => "Title",
'Value' => $title
),
array(
'Key' => "ShowName",
'Value' => $showName
),
array(
'Key' => "ShowDate",
'Value' => $showDate
),
array(
'Key' => "ShowTime",
'Value' => $showTime
)
),
'Resubscribe' => true,
'RestartSubscriptionBasedAutoResponders' => true
);
//print_r($subscriber);
$subwrap = new CS_REST_Subscribers($list_id, $this->auth);
$result = $subwrap->add($subscriber);
//var_dump($result->response);
echo "Result of POST /api/v3.1/subscribers/{list id}.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
}
return $result->response;
}
This code is working for me.You need to add campaign monitor class files in you project folder and use valid list id and api key.You can find you api key from manage account link and list id from click on (change name/type) below list title. Please wait some time to see in you list.
require_once 'csrest_subscribers.php';
$name=$_POST['name'];
$email=$_POST['email'];
$wrap = new CS_REST_Subscribers('Your list ID', 'Your API Key');
$result = $wrap->add(array(
'EmailAddress' => $email,
'Name' => $name,
'CustomFields' => array(), // no custom fields, can remove this line completely
'Resubscribe' => true
));
echo "Result of POST /api/v3/subscribers/{list id}.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
}
I am currently building a e-mail client (inbound and outbound sending) using Mandrill as the e-mail sending / inbound service and Laravel 3.x.
In order to send messages, I am using the HTTPful bundle with the Mandrill using the following code in my mail/compose POST method.
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
Link to better formatted code above: http://paste.laravel.com/m79
Now as far as I can tell from the API log, the request is correctly made (with the expected JSON) and a response of the following format is sent back:
[
{
"email": "test#test.com",
"status": "queued",
"_id": "longmessageID"
}
]
However, what I am trying to do is access the response from the request (specifically the _id attribute), which is in JSON. Now as far as I'm aware, the HTTPful class should do this automatically (using json_decode()). However, accessing:
$request->_id;
is not working and I'm not entirely sure how to get this data out (it is required so I can record this for soft-bounce, hard-bounce and rejection messages for postmaster-like functionality)
Any assistance would be appreciated.
Edit
Using the following code, results in the mail being sent but an error returned:
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
if ( $request[0]->status == "queued" ) {
$success = true;
}
Results in an exception being thrown: Cannot use object of type Httpful\Response as array
I must say, a huge thanks to Aiias for his assistance. I managed to fix this myself (I must have spent hours looking at this). For anyone who wants to know, the HTTPful bundle has a body array, where the response is kept. Therefore, the code below works:
$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array(
'key' => '{removedAPIkey}',
'message' => array (
'to' => array( array( "email" => $_to ) ),
'from_name' => Auth::user()->name,
'from_email' => Auth::user()->email,
'subject' => $_subject,
'html' => $_body
),
'async' => true
);
$request = Httpful::post($url)->sendsJson()->body($data)->send();
if ( $request->body[0]->status == "queued" ) {
$success = true;
}
Again, huge thanks to Aiias for clearing some major confusion up for me!