craftcms / mailgun

Mailgun mailer adapter for Craft CMS.
https://plugins.craftcms.com/mailgun
MIT License
28 stars 8 forks source link

Unable to send an email: Forbidden (code 401) #35

Open romainpoirier opened 9 months ago

romainpoirier commented 9 months ago

Description

I have a paid Mailgun account, with a verified domain. I can successfully send the Test Email from /admin/settings/email. However, I can't send from my Controller, while my config is correct.

This is the error I get:

[web.INFO] [yii\mail\BaseMailer::send] Sending email "Test" to "john@doe.com" {"memory":29395064} 
[web.ERROR] [yii\symfonymailer\Mailer::sendMessage] Unable to send an email: Forbidden (code 401). {"memory":29915280} 

Note: of course, I have used my own email address instead of john@doe.com.

And this is the code to send the email:

$email = 'john@doe.com';
$template = '_emails/test/test';
$subject = Craft::t('site', 'This is a test');
$htmlBody = Craft::$app->getView()->renderTemplate($template, []);

$view = Craft::$app->getView();
$html = $view->renderTemplate($template, $variables , View::TEMPLATE_MODE_SITE);

$response = Craft::$app
    ->getMailer()
    ->compose()
    ->setTo($email)
    ->setSubject($subject)
    ->setHtmlBody($html)
    ->send();

I also tried this instead:

$message = new Message();
$message->setTo($email);
$message->setSubject($subject);
$message->setHtmlBody($htmlBody);
$response = Craft::$app->getMailer()->send($message);

Steps to reproduce

  1. Setup Mailgun settings
  2. Try to send using the code above

Additional info

romainpoirier commented 9 months ago

Fixed: I've found out that the endpoint value was missing from my config/app.php file:

$settings->transportSettings = [
    'domain' => App::env('MAILGUN_DOMAIN'),
    'apiKey' => App::env('MAILGUN_API_KEY'),
    'endpoint' => App::env('MAILGUN_ENDPOINT')
];