Integrating Mailchimp API into your Laravel application can greatly enhance the functionality of your website by managing subscribers, sending emails via campaigns, and tracking email results.
This tutorial will guide you through the process of setting up Mailchimp API in a Laravel 5 application using the skovmand/mailchimp-laravel package. By the end of this tutorial, you will be able to create a simple email subscription system, send campaigns, and track email results using Mailchimp.
[lwptoc]
Step 1: Create MailChimp Account Setting
To get started, you need to have a MailChimp account. If you don’t have one yet, create a new account here. After signing up, create a new list by clicking on “Lists” in the menu and then “Create List”. After successfully creating the list, go to “Settings” > “List name and defaults” and copy your list ID. You will use this list ID later in the API.
Next, you need to obtain your API key. Click here to generate your API key. Open your .env
file and paste the following code:
MAILCHIMP_API_KEY=Your_API_Key_Here
Step 2: Install Package
In this step, install the skovmand/mailchimp-laravel package to use Mailchimp API methods. Run the following command in your terminal:
composer require skovmand/mailchimp-laravel
Now, add the provider path and alias path in the config/app.php
file:
return [
......
'providers' => [
......
Skovmand\Mailchimp\MailchimpServiceProvider::class,
],
.....
]
Step 3: Add Route
Add the following three routes in your routes/web.php
file for creating a simple example:
Route::get('manageMailChimp', 'MailChimpController@manageMailChimp');
Route::post('subscribe',['as'=>'subscribe','uses'=>'MailChimpController@subscribe']);
Route::post('sendCompaign',['as'=>'sendCompaign','uses'=>'MailChimpController@sendCompaign']);
Step 4: Add Controller
Create a MailChimpController.php
file in the app/Http/Controllers
directory and paste the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mailchimp;
class MailchimpController extends Controller
{
private $mailchimp;
private $listId;
public function __construct(Mailchimp $mailchimp)
{
$this->mailchimp = $mailchimp;
$this->listId = config('services.mailchimp.list_id');
}
public function subscribe(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
]);
try {
$this->mailchimp
->lists
->subscribe(
$this->listId,
['email' => $request->input('email')]
);
return redirect()->back()->with('success', 'Email Subscribed successfully');
} catch (\Mailchimp_List_AlreadySubscribed $e) {
return redirect()->back()->with('error', 'Email is Already Subscribed');
} catch (\Mailchimp_Error $e) {
return redirect()->back()->with('error', 'Error from MailChimp');
}
}
public function sendCompaign(Request $request)
{
$this->validate($request, [
'subject' => 'required',
'to_email' => 'required',
'from_email' => 'required',
'message' => 'required',
]);
try {
$options = [
'list_id' => $this->listId,
'subject' => $request->input('subject'),
'from_name' => $request->input('from_email'),
'from_email' => 'contact@freakyjolly.com',
'to_name' => $request->input('to_email'),
];
$content = [
'html' => $request->input('message'),
'text' => strip_tags($request->input('message')),
];
$campaign = $this->mailchimp->campaigns->create('regular', $options, $content);
$this->mailchimp->campaigns->send($campaign['id']);
return redirect()->back()->with('success', 'Send campaign successfully');
} catch (Exception $e) {
return redirect()->back()->with('error', 'Error from MailChimp');
}
}
}
subscribe()
: This method subscribes an email address to your Mailchimp list. It takes an email address as input, validates it, and attempts to add it to the list. If the email address is already subscribed, it returns an error message. If there’s any other issue with Mailchimp, it returns a general error message.
sendCompaign()
: This method sends an email campaign to the subscribers in your Mailchimp list. It takes the subject, to_email, from_email, and message as inputs, validates them, and attempts to create and send a campaign. If there’s an issue with Mailchimp, it returns a general error message.
Step 5: Add Blade file
Create a new Blade file mailchimp.blade.php
in the resources/views
directory and paste the code as provided below:
@extends('layouts.app')
@section('content')
<h2 class="text-center">MailChimp API Example</h2>
<div class="container">
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
@endif
@if ($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
@endif
<div class="row">
<div class="col-md-5">
<div class="well">
<form action="{{ route('subscribe') }}" method="post">
@csrf
<div>
<h3 class="text-center">Subscribe Your Email</h3>
<input class="form-control" name="email" id="email" type="email" placeholder="Your Email" required>
<br/>
<div class="text-center">
<button class="btn btn-info btn-lg" type="submit">Subscribe</button>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-7">
<div class="well well-sm">
<form action="{{ route('sendCompaign') }}" method="post" class="form-horizontal">
@csrf
<fieldset>
<legend class="text-center">Send Campaign</legend>
<!-- Subject input-->
<div class="form-group">
<label class="col-md-3 control-label" for="subject">Subject</label>
<div class="col-md-9">
<input id="subject" name="subject" type="text" placeholder="Your Subject" class="form-control">
</div>
</div>
<!-- To Email input-->
<div class="form-group">
<label class="col-md-3 control-label" for="to_email">To</label>
<div class="col-md-9">
<input id="to_email" name="to_email" type="text" placeholder="To " class="form-control">
</div>
</div>
<!-- From Email input-->
<div class="form-group">
<label class="col-md-3 control-label" for="from_email">From</label>
<div class="col-md-9">
<input id="from_email" name="from_email" type="text" placeholder="From " class="form-control">
</div>
</div>
<!-- Message body -->
<div class="form-group">
<label class="col-md-3 control-label" for="message">Your message</label>
<div class="col-md-9">
<textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea>
</div>
</div>
<!-- Form actions -->
<div class="form-group">
<div class="col-md-12 text-right">
<button type="submit" class="btn btn-primary btn-lg">Send Campaign</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
@endsection
Conclusion
You have now successfully integrated Mailchimp API into your Laravel 5 application. The skovmand/mailchimp-laravel package allows you to manage subscribers, send email campaigns, and track email results using Mailchimp.
By following this tutorial, you can create a simple email subscription system and send campaigns from your Laravel application.
Leave a Reply