How to send newly created campaign with mailchimp api v2? - php

I am using mailchimp api v2. I am using the mailchimp recommended full api v2 php wrapper. I am able to create a campaign, but not sure how to send it. With the send method, It wants the campaign id, but I am letting mailchimp create the campaign id when creating the campaign.
My create campaign code looks like this:
$api_key = "my_api_key";
require('Mailchimp.php');
//Create Campaign
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subject',
'from_email' => 'test#test.com',
'from_name' => 'From Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'didnt work';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
}

This seems to be working for me.
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subjects',
'from_email' => 'test#test.com',
'from_name' => 'From_Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'sorry';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
$mySend = $Mailchimp->campaigns->send($result['id']);
}

Related

Twilio how to get only messages sent by a Messaging Service

I am using the Twilio messaging service to send from multiple numbers.
I want to get messages that were sent from that messaging service.
I am trying to use stream, as I don't want thousands of messages
for each call.
Is there a way to get only messages that were sent out using a
particular messaging service?
$searcher = new TwilioLogRetriever;
$searcher->listMessagesForMessagingService('MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
TwilioLogRetriever
<?php
use Twilio\Rest\Client;
class TwilioLogRetriever {
function listMessagesForMessagingService($messagingServicesSid) {
$client = new Client(Configure::Read('twilio.accountSid'), Configure::read('twilio.authToken'));
$once = false;
$n = 0;
// Try specifying 'from' (just guessing)
foreach ($client->messages->stream(['from' => $messagingServicesSid]) as $message) {
++$n;
//echo $message->body . "\n";
$data = [
'from' => $message->from,
'to' => $message->to,
'direction' => $message->direction,
'messagingServiceSid' => $message->messagingServiceSid,
'numMedia' => $message->numMedia,
'numSegments' => $message->numSegments,
'price' => $message->price,
'priceUnit' => $message->priceUnit,
'sid' => $message->sid,
'status' => $message->status,
'body' => $message->body,
];
$data['dateCreated'] = $message->dateCreated->format('Y-m-d H:i:s');
$data['dateUpdated'] = $message->dateUpdated->format('Y-m-d H:i:s');
$data['dateSent'] = $message->dateSent->format('Y-m-d H:i:s');
if ( ! $once ) {
print_r($message);
$once = true;
}
}
$this->out(__METHOD__. " Found $n messages." );
}
function out($message ) {
echo $message . "\n";
}
}

Mailchimp Error: Bad Request - Your Campaign is not ready to send

I am using following tutorial to create campaign and send email in MailChimp using Php.
https://isabelcastillo.com/create-send-mailchimp-campaign-api-3
My Code piece are
require_once('../wp-load.php');
function isa_mailchimp_api_request( $endpoint, $type = 'POST', $body = '' )
{
// Configure --------------------------------------
$api_key = 'API KEY HERE'; // Changed API Key here
// STOP Configuring -------------------------------
$core_api_endpoint = 'https://<dc>.api.mailchimp.com/3.0/';
list(, $datacenter) = explode( '-', $api_key );
$core_api_endpoint = str_replace( '<dc>', $datacenter, $core_api_endpoint );
$url = $core_api_endpoint . $endpoint;
//print_r($url );
$request_args = array(
'method' => $type,
'timeout' => 20,
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'apikey ' . $api_key
)
);
if ( $body ) {
$request_args['body'] = json_encode( $body );
}
$request = wp_remote_post( $url, $request_args );
$response = is_wp_error( $request ) ? false : json_decode( wp_remote_retrieve_body( $request ) );
echo '<pre>';
print_r($response);
return $response;
}
function isa_create_mailchimp_campaign( $list_id, $subject ) {
$reply_to = 'info#newslume.com';
$from_name = 'NewsLume';
$subject= 'Another new test message 14 17';
$campaign_id = '';
$body = array(
'recipients' => array('list_id' => $list_id),
'type' => 'regular',
'settings' => array('subject_line' => $subject,
'title' => 'a test title NewsLUme',
'reply_to' => $reply_to,
'from_name' => $from_name,
'use_conversation'=> false,
'to_name'=> 'sajid',
'auto_footer'=> false,
'inline_css'=> false,
'auto_tweet'=> false,
'drag_and_drop'=> false
)
);
$create_campaign = isa_mailchimp_api_request( 'campaigns', 'POST', $body );
if ( $create_campaign ) {
if ( ! empty( $create_campaign->id ) && isset( $create_campaign->status ) && 'save' == $create_campaign->status ) {
// The campaign id:
$campaign_id = $create_campaign->id;
}
}
return $campaign_id ? $campaign_id : false;
}
function isa_set_mail_campaign_content( $campaign_id, $template_content ) {
$set_content = '';
$set_campaign_content = isa_mailchimp_api_request( "campaigns/$campaign_id/content", 'PUT', $template_content );
if ( $set_campaign_content ) {
if ( ! empty( $set_campaign_content->html ) ) {
$set_content = true;
}
}
return $set_content ? true : false;
}
$list_id='my_list_id_here'; // LIST HERE
$campaign_id = isa_create_mailchimp_campaign( $list_id, $subject );
if ( $campaign_id ) {
// Set the content for this campaign
$template_content = array(
'template' => array(
// The id of the template to use.
'id' => 47615, // INTEGER
'sections' => array(
'tst_content' => 'THIS IS THE CONTENT BODY OF MY EMAIL MESSAGE.'
)
)
);
$set_campaign_content = isa_set_mail_campaign_content( $campaign_id, $template_content );
if ( $set_campaign_content ) {
$send_campaign = isa_mailchimp_api_request( "campaigns/$campaign_id/actions/send", 'POST' );
if ( empty( $send_campaign ) ) {
// Campaign was sent!
} elseif( isset( $send_campaign->detail ) ) {
$error_detail = $send_campaign->detail;
}
}
}
I have updated all values, including API KEY, List ID, template ID etc. but still i am getting errors
Here is Error object
stdClass Object
(
[type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
[title] => Bad Request
[status] => 400
[detail] => Your Campaign is not ready to send.
[instance] => 89dc8734-2611-4f3b-a4f7-d18bd181bded
)
I checked in Mail Chimp, campaigns are created there but they are saved as Draft.
Here are my API Logs
API Logs can be seen by clicking link below
https://drive.google.com/file/d/0BwIWuJmCDI1vNHgtVm9TQm1FMVU/view?usp=drivesdk
I am able to create campaign, set a template to campaign but i cannot send emails. My Domain is also verified and authenticated with Mailchimp using guidelines.
Please check and suggest a solution
While the "Your Campaign is not ready to send" message isn't very helpful, you can check for a more detailed message in MailChimp itself. Edit the draft that the API created, and navigate to the final Confirm step. You'll see a checklist where most of the items passed, but there will also be an item that explains why the campaign failed.
When I attempted to replicate the issue, the campaign failed to send because there was some default placeholder text left unchanged in the template. Since the code you posted only sets the content for one block, this is probably the same issue you're having.
Hope this helps!

Campaign Monitor php sdk - add Subscribe bug - no longer showing on list

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>';
}

Forward an email which decode from mandrill webhook, by php SwiftMailer

I'm using mandrill to manage my website emails.But I also want to use a mailbox like yahoo or google so I set a route in mandrill which forward inbound emails that will send to info#mydomain.com, to my default mail box(myEmail#ymail.com).I wrote a PHP code which receive an email, decode it, and forward it to a my email. I use SwiftMailer to send SMTP email.
It works nice for emails without any attachment.But there is a strange problem with attachments.They deliver corruptly.I can not open them.
I search throughly and test a lot, but unfortunately couldn't find the problem.
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
// ----------------- Send ----------------------------------------
include_once "swiftmailer-master/lib/swift_required.php";
$subject = $mail->msg->subject . " From " . $mail->msg->from_email;
$from = array('info#myDomain.ir' =>'myDomain');
$to = array(
'myEmail#yahoo.com' => 'Hamed Gh'
);
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 25,tls);
$transport->setUsername('username');
$transport->setPassword('***********');
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
//I think there is a problem here!!
foreach ($mail->msg->attachments as $attachment) {
$myType = $attachment->type;
$myName = $attachment->name;
$myContent = $attachment->content;
$attachment = Swift_Attachment::newInstance()
->setFilename($myName)
->setContentType($myType)
->setBody($myContent)
;
$message->attach($attachment);
}
$body = $mail->msg->html;
$message->setBody($body, 'text/html');
$message->setTo($to);
$text = "Mandrill speaks plaintext";
$message->addPart($text, 'text/plain');
if($recipients = $swift->send($message, $failures) )
{
echo 'Message successfully sent!';
} else {
echo "There was an error:\n";
print_r($failures);
}
?>
At the end I couldn't find the problem with SwiftMailer but I could answer my need with mandrill API,
this code works for me:
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
require 'mandrill/src/Mandrill.php';
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
$attachments = array();
foreach ($mail->msg->attachments as $attachment) {
$attachments[] = array(
'type' => $attachment->type,
'name' => $attachment->name,
'content' => $attachment->content,
);
}
$headers = array();
// Support only Reply-to header
if(isset($mail->msg->headers->{'Reply-to'})) {
$headers[] = array('Reply-to' => $mail->msg->headers->{'Reply-to'});
}
// ----------------- Send ----------------------------------------
try {
$mandrill = new Mandrill('-------------');
$message = array(
'html' => $mail->msg->html,
'text' => 'Example text content',
'subject' => $mail->msg->subject . " From " . $mail->msg->from_email,
'from_email' => 'info#mydomain.com',
'from_name' => 'info',
'to' => array(
array(
'email' => 'me#yahoo.com',
'name' => 'me',
'type' => 'to'
)
),
'headers' => array('Reply-To' => 'info#mydomain.com'),
'important' => false,
'track_opens' => null,
'track_clicks' => null,
'auto_text' => null,
'auto_html' => null,
'inline_css' => null,
'url_strip_qs' => null,
'preserve_recipients' => null,
'view_content_link' => null,
'bcc_address' => null,
'tracking_domain' => null,
'signing_domain' => null,
'return_path_domain' => null,
'merge' => true,
'attachments' => $attachments
);
$async = false;
$ip_pool = 'Main Pool';
$send_at = null;
$result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
} catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
?>

MailChimp API 2.0 Error Response for existing E-Mail Address

I am trying to get a response from MailChimp to return a message to the Subscriber. The subscribtion is working fine but I do not get any response from MailChimp. I am a Noob at PHP so do I neeed to use JSON or can it be done like in my Code with PHP?
$MailChimp = new \drewm\MailChimp('12122338484487841-us1');
$result = $MailChimp->call('lists/subscribe', array(
'id' => '1123334444',
'email' => array('email'=>$check_mail['customers_email_address']),
'merge_vars' => array('FNAME'=>$check_mail['customers_firstname'], 'LNAME'=>$check_mail['customers_lastname']),
'double_optin' => true,
'update_existing' => false,
'replace_interests' => false,
'send_welcome' => true,
));
// CHECK MAILCHIMP IF EMAIL EXIST
if( $result === false ) {
return 'You have already subscribed to the List';
}
else if( isset($result->status) && $result->status == 'error' ) {
// Error info: $result->status, $result->code, $result->name, $result->error
}
// CHECK MAILCHIMP IF EMAIL EXIST
Thanks
Cool , then you can check like..
if( $result['name'] === 'List_AlreadySubscribed' ) {
return $result['error'];// which returns "mail#example.com is already subscribed to list SyncTest. Click here to update your profile." as a string.
}

Categories