zeckdude zeckdude - 6 months ago 42
PHP Question

Using Laravel 5, how can I find out if a Mailgun email was sent successfully?

I'm using the native Mailgun driver in Laravel 5 to send an email

\Mail::send('emails.notification', $data, function($message) use ($data)
{
$message->to('name@gmail.com', 'Joe Bob')->subject("Headline here");
});


That works well and the emails are being received, but I would like to know how I can get a response from Mailgun letting me know that the email was sent.

How can I go about getting that information?

Answer

I figured out the solution and it's actually quite simple.

With Laravel (Using the Bogardo Mailgun Package):

$to_name = "Jim Bob";
$to_email = "jimbob@gmail.com";
$subject = "Howdy everyone!";

// Send the email and capture the response from the Mailgun server
$response = Mailgun::send('emails.transactional', array('body' => $body), function($message) use($to_email, $to_name, $subject)
{
  $message->to($to_email, $to_name)->subject($subject);
});

// HTTP Response Code 200 means everything worked as expected
if ($response->http_response_code === 200) {
  echo "Woohoo! The message sent!";
}


In plain ol' PHP (Using the official Mailgun PHP SDK):

// Config Information
$mailgun = new Mailgun("key-v876876dfsv876csd8768d876cfsd4");
$domain = "mg.mydomain.com";

// Prepare the necessary information to send the email
$send_data = array(
  'from' => $from_name . ' <' . $from_email . '>',
  'to' => $to_name . ' <' . $to_email . '>',
  'subject' => $subject,
  'html' => $html
);

// Send the email and capture the response from the Mailgun server
$response = $mailgun->sendMessage($domain, $send_data);

// HTTP Response Code 200 means everything worked as expected
if ($response->http_response_code === 200) {
  echo "Woohoo! The message sent!";
}

Check out a list of all Mailgun HTTP Response Codes: (https://documentation.mailgun.com/api-intro.html?highlight=401#errors)

Comments