使用 Laravel 5,如何确定 Mailgun 电子邮件是否已成功发送?

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

我在 Laravel 5 中使用本机 Mailgun 驱动程序发送电子邮件

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

效果很好,正在接收电子邮件,但我想知道如何从 Mailgun 获得回复,让我知道电子邮件已发送。

我怎样才能获得这些信息?

要了解电子邮件的状态,您可以使用 Mailgun webhook。在 Mailgun 管理区域中,您可以指定一个 Webhook url,Mailgun 在处理完您的电子邮件后将 post 连接到该 Webhook。

确保您用作 webhook 的任何 url 都存在于您的应用程序中,并且在您使用的任何控制器中都有路由和方法。一旦您的应用程序收到 posted 数据,您就可以解析发送的数据并确定电子邮件的状态。然后您可以更新您的数据库或任何您需要做的事情。

要识别您需要在电子邮件中添加一些自定义 headers 的电子邮件,以便您稍后识别它。

有关如何执行此操作的更多详细信息,请参阅此答案:Using Laravel's Mailgun driver, how do you (gracefully) send custom data and tags with your email?

webhook url 需要在线才能工作,所以如果你在本地使用 laravell homestead 进行测试,你可以看看 ngrok,它允许你隧道你的本地环境到一个 url ,它将用于测试目的。

我想出了解决办法,其实很简单。

With Laravel(使用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 (使用官方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!";
}

查看所有 Mailgun HTTP 响应代码的列表:(https://documentation.mailgun.com/api-intro.html?highlight=401#errors)