使用 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 webhooks。在Mailgun管理区域中,您可以指定Mailgun在处理您的电子邮件后将发布到的网络钩子URL。

确保应用程序中存在用作 Webhook 的任何 url,并且在您使用的任何控制器中都有路由和方法。应用程序收到发布的数据后,您可以解析发送的数据并确定电子邮件的状态。然后,您可以更新数据库或需要执行的任何操作。

要确定哪封电子邮件,您需要在电子邮件中添加一些自定义标头,以便以后识别它。

有关如何执行此操作的更多详细信息,请参阅此答案: 使用 Laravel 的 Mailgun 驱动程序,您如何(优雅地)通过电子邮件发送自定义数据和标签?

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

我想

出了解决方案,它实际上非常简单。

使用

Laravel(使用Bogardo Mailgun软件包):

$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!";
}

在普通的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!";
}

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