How to send mail using mailchimp in codeigniter
To send mail using Mailchimp in CodeIgniter, you'll need to follow these steps:
Step 1: Set up your Mailchimp account
- Create a Mailchimp account and set up a new list.
- Get your API key from the Mailchimp dashboard.
Step 2: Install the Mailchimp PHP library
- You can install the Mailchimp PHP library using Composer:
composer require mailchimp/mailchimp
- Alternatively, you can download the library from the Mailchimp GitHub repository and include it in your CodeIgniter project.
Step 3: Configure your Mailchimp API key in CodeIgniter
- In your CodeIgniter project, create a new file called
mailchimp.php
in theapplication/libraries
directory. - In this file, add the following code:
<?php
class Mailchimp {
private $api_key;
private $list_id;
public function __construct($api_key, $list_id) {
$this->api_key = $api_key;
$this->list_id = $list_id;
}
public function send_email($email, $subject, $message) {
// Set up the Mailchimp API client
$client = new \Mailchimp\Mailchimp($this->api_key);
// Set up the email campaign
$campaign = array(
'type' => 'regular',
'recipients' => array(
'list_id' => $this->list_id,
'segment_opts' => array(
'conditions' => array(
array(
'condition_type' => 'equals',
'field' => 'email',
'value' => $email
)
)
)
),
'settings' => array(
'subject_line' => $subject,
'from_name' => 'Your Name',
'from_email' => '[email protected]',
'reply_to' => '[email protected]'
),
'template' => array(
'name' => 'Your Template Name',
'sections' => array(
array(
'content' => $message
)
)
)
);
// Send the email campaign
$response = $client->post('campaigns', array('campaign' => $campaign));
// Check if the email was sent successfully
if ($response->getStatusCode() == 200) {
return true;
} else {
return false;
}
}
}
**Step 4: Use the Mailchimp library in your CodeIgniter controller**
* In your CodeIgniter controller, create a new method that uses the Mailchimp library to send an email.
* For example:
```php
<?php
class My_controller extends CI_Controller {
public function send_email() {
$api_key = 'your_api_key';
$list_id = 'your_list_id';
$email = '[email protected]';
$subject = 'Test Email';
$message = 'This is a test email';
$mailchimp = new Mailchimp($api_key, $list_id);
if ($mailchimp->send_email($email, $subject, $message)) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email.';
}
}
}
That's it! With these steps, you should be able to send mail using Mailchimp in CodeIgniter.