Search code examples
laravellaravel-4mailgunlaravel-4.2

Laravel 4.2 - Mailgun error "Client error response [url] https://api.mailgun.net/v2/{domain_name}/messages.mime [status code] 400 "


Started getting this error when trying to send out emails in Laravel 4.2 with Mailgun. This has been working fine for the longest time, and no changes have been made to the code.

Error: "Client error response [url] https://api.mailgun.net/v2/{domain_name}/messages.mime [status code] 400 [reason phrase] BAD REQUEST"

config/mail.php

'driver' => 'mailgun',
'host' => 'smtp.mailgun.org',
'port' => 587,
'from' => array('address' => '[email protected]', 'name' => 'Domain Portal'),
'encryption' => 'tls',
'username' => '[email protected]',
'password' => 'xxxxxxxxx',
'sendmail' => '/usr/sbin/sendmail -bs',
'pretend' => false,

config/services.php

'mailgun' => array(
  'domain' => 'my-domain.ca',
  'secret' => 'key-xxxxxxxx',
),

composer.json

"laravel/framework": "4.2.*",
"guzzlehttp/guzzle": "5.0.3",

controller.php

if(isset($email_data['recipient_email']) && $email_data['recipient_email']) {
Mail::send($mailView, $data, function($message) use ($email_data, $attachments)
{
  $message->from($email_data['email_sender_address'], $email_data['email_sender_name'])
    ->to($email_data['recipient_email'], $email_data['recipient_name'])
    ->subject($email_data['subject']);


  if ($email_data['bcc']) {
    $message->bcc($email_data['bcc']);
  }

  if ($attachments) {
    foreach ($attachments as $a) {
      $message->attach($a);
    }
  }

  $message->getHeaders()->addTextHeader('X-Mailgun-Variables', '{"chapter_id": '.$email_data['chapter_id'].'}');
  $message->getHeaders()->addTextHeader('x-mailgun-native-send', true);
});
}

This is really bizarre, it seems to work fine when I test it locally, and it sometimes will send out emails, but other times I will just get the error message.


Solution

  • Turns out the problem was that the recipient_name had some special characters in it, and that was breaking the mail request. I solved this by not including the recipient_name and instead just sending it straight to their email.