Send Email using Mailjet(Alternative to Gmail SMTP Server) in PHP

The website owners regularly need to send emails to the users. If you are using PHP’s mail() function then soon you will realize your emails are ending in the spam and not in the user’s inbox. As a result, most of the users are missing your important emails. To resolve this problem you must use SMTP servers to send your website emails.

Gmail SMTP server is a quite popular choice among people. But there are 2 problems using this Google service. First, you couldn’t set the ‘from’ address while sending the email. Gmail set your email address(Google email id) as the sender. You probably want to have your domain email as a sender. Second, you need to turn on the ‘allow less secure apps’ setting which is not recommended by Google.

To avoid these limitations, I found an alternate solution for the Gmail SMTP server which is Mailjet. Mailjet is an email delivery service for marketing and developer teams. We can easily send emails using Mailjet in PHP. They provide their own email API to shoot emails. You can also use the Mailjet SMTP service and send your website emails.

Getting Started

Mailjet provides a quota of 6000 free emails per month(200 emails per day). For small businesses, this free quota is sufficient. If your business needs more emails then check out their pricing page.

To get started, you need to register with Mailjet. During the signup process, you will be asked to choose the sending method. In this tutorial, we discuss both methods – Email API and SMTP relay. For now, pick up the API option.

Choose API Option

Follow the next steps. From the below screen hit the ‘Get started’ button under the developer section.

Mailjet Get Started

To grab your API keys, go to ‘Account Settings’. On the next page, under the REST API section click on the ‘Master API key & Sub API key management’. Copy the API key and Secret key which are required in the next steps.

API Keys

Mailjet allows us to set the sender address. Under ‘Senders & Domains’ click on ‘Add a Sender Domain or Addresses’ and on the next page add a sender address.

Sender Address

If you are setting an address other than your account email then you will get an email for verification.

Send Email using Mailjet via cURL in PHP

We are ready with the Mailjet API keys and ready to send emails using Mailjet and cURL in PHP. Make sure you have cURL enabled on your server else the following code will not work as expected. Replace the placeholders with the actual values before running the below code.

<?php
$body = [
    'Messages' => [
        [
        'From' => [
            'Email' => "SENDER_EMAIL_ADDRESS",
            'Name' => "SENDER_NAME"
        ],
        'To' => [
            [
                'Email' => "RECIPIENT_EMAIL_ADDRESS",
                'Name' => "RECIPIENT_NAME"
            ]
        ],
        'Subject' => "Greetings from Mailjet.",
        'HTMLPart' => "<h3>Dear User, welcome to Mailjet!</h3><br />May the delivery force be with you!"
        ]
    ]
];
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_URL, "https://api.mailjet.com/v3.1/send");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_USERPWD, "API_KEY:SECRET_KEY");
$server_output = curl_exec($ch);
curl_close ($ch);
 
$response = json_decode($server_output);
if ($response->Messages[0]->Status == 'success') {
    echo "Email sent successfully.";
}

Send Email using Mailjet via Guzzle in PHP

You may want to use Guzzle instead of cURL to send your emails. Probably your application is running on a framework or CMS where you are using a Composer for managing libraries. In that case, Guzzle would be a better option over cURL.

Install the Guzzle library by running the command:

composer require guzzlehttp/guzzle

After installing the library, using the code below you can send emails using Guzzle and Mailjet in PHP.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;
 
$body = [
    'Messages' => [
        [
        'From' => [
            'Email' => "SENDER_EMAIL_ADDRESS",
            'Name' => "SENDER_NAME"
        ],
        'To' => [
            [
                'Email' => "RECIPIENT_EMAIL_ADDRESS",
                'Name' => "RECIPIENT_NAME"
            ]
        ],
        'Subject' => "Greetings from Mailjet.",
        'HTMLPart' => "<h3>Dear User, welcome to Mailjet!</h3><br />May the delivery force be with you!"
        ]
    ]
];
 
$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'https://api.mailjet.com/v3.1/',
]);
 
$response = $client->request('POST', 'send', [
    'json' => $body,
    'auth' => ['API_KEY', 'SECRET_KEY']
]);
 
if($response->getStatusCode() == 200) {
    $body = $response->getBody();
    $response = json_decode($body);
    if ($response->Messages[0]->Status == 'success') {
        echo "Email sent successfully.";
    }
}

Send Email using Mailjet SMTP Server and PHPMailer

In the above steps, we discussed using the Mailjet email API for sending emails. In this section, I show you how to use the Mailjet SMTP server to send an email to users.

From the dashboard click on ‘Setup my SMTP’. On the next page, you will get all SMTP credentials.

Setup SMTP

Next, install the PHPMailer library in your project using the command below:

composer require phpmailer/phpmailer

Write the below code in your PHP file which will send an email through the Mailjet SMTP server.

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
 
require_once "vendor/autoload.php";
 
$mail = new PHPMailer(true);
 
try {
    $mail->isSMTP();
    $mail->Host = 'MAILJET_SMTP_SERVER'; // host
    $mail->SMTPAuth = true;
    $mail->Username = 'API_KEY'; //username
    $mail->Password = 'SECRET_KEY'; //password
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587; //smtp port
   
    $mail->setFrom('SENDER_EMAIL_ADDRESS', 'SENDER_NAME');
    $mail->addAddress('RECIPIENT_EMAIL_ADDRESS', 'RECIPIENT_NAME');
 
    $mail->isHTML(true);
    $mail->Subject = 'Email Subject';
    $mail->Body    = '<b>Email Body</b>';
 
    $mail->send();
    echo 'Email sent successfully.';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: '. $mail->ErrorInfo;
}

Send Email using Mailjet SMTP Server and Symfony Mailer

Like PHPMailer, Symfony Mailer is also a popular library used for sending an email using the SMTP server. You can use this library to send your emails through the Mailjet SMTP server.

Install the Symfony Mailer library using the command:

composer require symfony/mailer

Symfony Mailer allows you to use third-party providers like Mailjet, Gmail, Amazon SES, etc. In our case, install the Mailjet provider through the command:

composer require symfony/mailjet-mailer

After this, using the code below your email will be sent through the Mailjet SMTP server.

<?php
require_once 'vendor/autoload.php';

use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;

try {
    $transport = Transport::fromDsn('mailjet+smtp://'.urlencode('API_KEY').':'.urlencode('SECRET_KEY').'@default');
    $mailer = new Mailer($transport);

    $email = (new Email())
        ->from('SENDER_NAME <SENDER_EMAIL_ADDRESS>')
        ->to('RECIPIENT_EMAIL_ADDRESS')
        ->subject('Email Subject')
        ->html('<b>Email Body</b>');

    $mailer->send($email);

    echo "Email sent successfully.";
} catch(Exception $e) {
    echo $e->getMessage();
}

Replace the placeholders with the actual values and test the code. The recipient should have received the email.

Conclusion

In this tutorial, we studied how to send emails in PHP using Mailjet’s API and SMTP relay. We discussed sending an email via Mailjet email API using cURL and Guzzle. Mailjet provides an SMTP server so we have written a code that uses the Mailjet SMTP server and sends an email to the users. Now, based on these options, users can pick any of the options that best fit them.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

3 thoughts on “Send Email using Mailjet(Alternative to Gmail SMTP Server) in PHP

Leave a Reply

Your email address will not be published.