【问题标题】:Using Laravel 5, how can I find out if a Mailgun email was sent successfully?使用 Laravel 5,如何确定 Mailgun 电子邮件是否发送成功?
【发布时间】:2016-06-16 10:45:45
【问题描述】:

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

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

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

我该如何获取这些信息?

【问题讨论】:

    标签: php api laravel-5 mailgun


    【解决方案1】:

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

    使用 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)

    【讨论】:

      【解决方案2】:

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

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

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

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

      webhook url 需要激活才能正常工作,因此如果您使用 laravell homestead 在本地进行测试,您可以查看 ngrok,它允许您将本地环境隧道传输到可用于测试目的的 url。

      【讨论】:

      • 感谢您的回答,但幸运的是,这并不难。 Webhook 非常适合其他更高级的事情,但不仅仅是为了从 Mailgun 获得成功响应。请参考我发布的答案。
      • 200 响应是否表明 Mailgun 已成功收到您的请求,然后 Mailgun 继续处理电子邮件,并为每封邮件提供已发送、失败、退回等状态。我不能 100% 确定使用您的方法是否成功。也许您可以尝试向它发送一个不存在的电子邮件地址,如果它给出 200 响应,请检查 mailgun 日志,它会显示发送失败。
      猜你喜欢
      • 2017-10-12
      • 1970-01-01
      • 2013-11-06
      • 2021-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2019-10-18
      • 2016-09-26
      相关资源
      最近更新 更多