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

The website owners regularly need to send emails to our users. If you are using PHP’s mail() function for sending emails 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 not noticing your important emails. To resolve this problem you must use SMTP servers to send your emails.

Gmail SMTP server is a quite popular choice among developers. 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 address. 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 may also use their SMTP service.

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.

During the signup process, you will be asked to choose the sending method. In this tutorial, we discuss both Email API and SMTP relay so, 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 our API keys and ready to send our email 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 code below.

<?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 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.

In this scenarios 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 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

Let’s see how to use SMTP credentials in PHP and send an email. At first, install the PHPMailer library in your project by running the command below:

composer require phpmailer/phpmailer

Next, write the below code in your PHP file which will send an email through your SMTP credentials.

<?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 has been sent.';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: '. $mail->ErrorInfo;
}

Send Email Using Mailjet SMTP Server and Swift Mailer

Like PHPMailer, Swift Mailer is also a popular library useful for sending an email using the SMTP server. You should have PHP version 7.0 or higher to send emails using the Swift Mailer library. Install the Swift Mailer library using the command:

composer require swiftmailer/swiftmailer

Upon library installation, using the Mailjet SMTP server credentials you can send the email through the code below.

<?php
require_once 'vendor/autoload.php';
 
try {
    // Create the Transport
    $transport = (new Swift_SmtpTransport('MAILJET_SMTP_SERVER', 587, 'tls'))
      ->setUsername('API_KET')
      ->setPassword('SECRET_KEY')
    ;
 
    // Create the Mailer using your created Transport
    $mailer = new Swift_Mailer($transport);
 
    // Create a message
    $body = '<b>Email Body</b>';
 
    $message = (new Swift_Message('Email Subject'))
      ->setFrom(['SENDER_EMAIL_ADDRESS' => 'SENDER_NAME'])
      ->setTo(['RECIPIENT_EMAIL_ADDRESS'])
      ->setBody($body)
      ->setContentType('text/html')
    ;
 
    // Send the message
    $mailer->send($message);
 
    echo 'Email has been sent.';
} 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 Mailjet’s email 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. So, based on these 3 options, users can pick any of the options depending on their project requirement.

Related Articles

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

2 thoughts on “Send Email Using Mailjet(Alternative to Gmail SMTP Server) in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *