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

时间:2016-03-03 08:13:10

标签: php api laravel-5 mailgun

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

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

效果很好,电子邮件正在收到,但我想知道如何从Mailgun收到回复,告诉我电子邮件已发送。

如何获取该信息?

2 个答案:

答案 0 :(得分:2)

我找到了解决方案,实际上非常简单。

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


在普通的'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

答案 1 :(得分:1)

要了解电子邮件的状态,您可以使用Mailgun webhooks。在Mailgun管理区域中,您可以指定Mailgun在处理完您的电子邮件后将发布的webhook网址。

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

要确定在电子邮件中添加一些自定义标题所需的电子邮件,以便日后识别。

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

webhook网址需要处于活动状态,因此如果您在本地使用laravell宅基地进行测试,您可以查看ngrok,它允许您将当地环境隧道传输到可用于测试目的的网址。