Skip to content

Instantly share code, notes, and snippets.

@ToshY
Created September 5, 2020 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToshY/9b52d87db67efb62c284884361acaed5 to your computer and use it in GitHub Desktop.
Save ToshY/9b52d87db67efb62c284884361acaed5 to your computer and use it in GitHub Desktop.
Simple MailJet API v3 email sender in PHP
<?php
class MailJetAPI{
/*
* Simpel MailJet mailer with the v3 API
*/
private const BASE_URL = 'https://api.mailjet.com/v3.1/send';
private $key;
private $secret;
public function __construct($user_key, $user_secret){
# Mailjet credentials
$this->key = $user_key;
$this->secret = $user_secret;
}
public function sendEmail( $subject, $message, $to_mail, $from_mail, $from_name = '' ){
# Send MailJet email
$ch = curl_init( self::BASE_URL );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt($ch, CURLOPT_USERPWD, $this->key . ':' . $this->secret );
# Message content
$msg = ['Messages' => [['From' => ['Email' => $from_mail,'Name' => (empty($from_name) ? $from_mail : $from_name)],'To' => [['Email' => $to_mail]],'Subject' => $subject,'HTMLPart' => $message]]];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $msg ) );
# Headers
$headers = ['Content-Type: application/json'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
# Execute and check response code
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( curl_errno($ch) ) return curl_error($ch);
curl_close($ch);
return json_decode( $result, FALSE );
}
}
# MailJet mailer
$mailer = new MailJetAPI('ab12cd34ef56gh78ab12cd34ef56gh78','87hg65fe43dc21ba87hg65fe43dc21ba');
# Send email
$mail_result = $mailer->sendEmail('Hello New User', '<b>Welcome to our Service</b>', 'newuser@example.com', 'admin@domain.com', 'The Admin');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment