1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-15 07:33:04 +01:00
invoiceninja/app/Jobs/Mail/NinjaMailerJob.php

816 lines
28 KiB
PHP
Raw Normal View History

2021-02-14 11:43:44 +01:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2024-04-12 06:15:41 +02:00
* @copyright Copyright (c) 2024. Invoice Ninja LLC (https://invoiceninja.com)
2021-02-14 11:43:44 +01:00
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
2021-02-14 11:43:44 +01:00
*/
namespace App\Jobs\Mail;
use App\DataMapper\Analytics\EmailFailure;
2021-04-24 15:19:46 +02:00
use App\DataMapper\Analytics\EmailSuccess;
2021-02-16 13:56:12 +01:00
use App\Events\Invoice\InvoiceWasEmailedAndFailed;
2021-02-18 00:30:31 +01:00
use App\Events\Payment\PaymentWasEmailedAndFailed;
2021-02-14 11:43:44 +01:00
use App\Jobs\Util\SystemLogger;
use App\Libraries\Google\Google;
use App\Libraries\MultiDB;
use App\Models\ClientContact;
2021-05-13 15:37:25 +02:00
use App\Models\Company;
2021-02-18 00:30:31 +01:00
use App\Models\Invoice;
use App\Models\Payment;
2021-02-14 11:43:44 +01:00
use App\Models\SystemLog;
use App\Models\User;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
2021-09-06 05:07:11 +02:00
use GuzzleHttp\Exception\ClientException;
2021-02-14 11:43:44 +01:00
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
2023-02-16 02:36:09 +01:00
use Illuminate\Support\Facades\Cache;
2021-02-14 11:43:44 +01:00
use Illuminate\Support\Facades\Mail;
use Turbo124\Beacon\Facades\LightLogs;
/*Multi Mailer implemented*/
class NinjaMailerJob implements ShouldQueue
{
2024-01-14 05:05:00 +01:00
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
use MakesHash;
2021-02-14 11:43:44 +01:00
public $tries = 4; //number of retries
2021-02-14 11:43:44 +01:00
public $deleteWhenMissingModels = true;
2023-08-19 08:44:17 +02:00
/** @var null|\App\Models\Company $company **/
2023-04-27 00:48:45 +02:00
public ?Company $company;
2021-06-17 09:48:23 +02:00
private $mailer;
2023-01-11 09:29:27 +01:00
protected $client_postmark_secret = false;
protected $client_mailgun_secret = false;
protected $client_mailgun_domain = false;
2023-12-18 19:37:13 +01:00
protected $client_brevo_secret = false;
2023-01-11 09:29:27 +01:00
2024-01-23 21:31:06 +01:00
public function __construct(public ?NinjaMailerObject $nmo, public bool $override = false)
2021-02-14 11:43:44 +01:00
{
}
public function backoff()
{
2024-04-03 08:37:21 +02:00
return [rand(5, 29), rand(30, 59), rand(61, 100), rand(180, 500)];
}
2021-02-14 11:43:44 +01:00
public function handle()
{
2021-02-16 13:56:12 +01:00
/*Set the correct database*/
2021-02-14 11:43:44 +01:00
MultiDB::setDb($this->nmo->company->db);
/* Serializing models from other jobs wipes the primary key */
2023-08-08 10:56:31 +02:00
$this->company = Company::query()->where('company_key', $this->nmo->company->company_key)->first();
2021-05-13 15:37:25 +02:00
2023-11-01 00:34:02 +01:00
/* Set the email driver */
$this->setMailDriver();
2023-01-11 09:29:27 +01:00
/* If any pre conditions fail, we return early here */
2023-02-16 02:36:09 +01:00
if (!$this->company || $this->preFlightChecksFail()) {
2021-08-07 12:56:42 +02:00
return;
2023-02-16 02:36:09 +01:00
}
2023-01-11 09:29:27 +01:00
/* Run time we set Reply To Email*/
2021-02-24 00:39:37 +01:00
if (strlen($this->nmo->settings->reply_to_email) > 1) {
2023-02-16 02:36:09 +01:00
if (property_exists($this->nmo->settings, 'reply_to_name')) {
2021-05-03 06:50:55 +02:00
$reply_to_name = strlen($this->nmo->settings->reply_to_name) > 3 ? $this->nmo->settings->reply_to_name : $this->nmo->settings->reply_to_email;
2023-02-16 02:36:09 +01:00
} else {
2021-05-03 06:50:55 +02:00
$reply_to_name = $this->nmo->settings->reply_to_email;
2023-02-16 02:36:09 +01:00
}
2021-05-03 06:50:55 +02:00
2021-02-24 00:39:37 +01:00
$this->nmo->mailable->replyTo($this->nmo->settings->reply_to_email, $reply_to_name);
2024-03-17 08:43:40 +01:00
} elseif (isset ($this->nmo->invitation->user)) {
$this->nmo->mailable->replyTo($this->nmo->invitation->user->email, $this->nmo->invitation->user->present()->name());
2024-02-13 05:25:18 +01:00
} else {
$this->nmo->mailable->replyTo($this->company->owner()->email, $this->company->owner()->present()->name());
2021-05-13 00:13:33 +02:00
}
2023-01-11 09:29:27 +01:00
/* Run time we set the email tag */
2022-08-07 09:34:23 +02:00
$this->nmo->mailable->tag($this->company->company_key);
2023-01-11 09:29:27 +01:00
/* If we have an invitation present, we pass the invitation key into the email headers*/
2023-02-16 02:36:09 +01:00
if ($this->nmo->invitation) {
2022-08-17 09:18:30 +02:00
$this->nmo
2023-12-18 19:37:13 +01:00
->mailable
->withSymfonyMessage(function ($message) {
$message->getHeaders()->addTextHeader('x-invitation', $this->nmo->invitation->key);
});
2022-08-17 09:18:30 +02:00
}
2021-02-14 11:43:44 +01:00
//send email
try {
2023-12-18 19:37:13 +01:00
nlog("Trying to send to {$this->nmo->to_user->email} " . now()->toDateTimeString());
nlog("Using mailer => " . $this->mailer);
2021-06-23 00:17:22 +02:00
2023-01-11 09:29:27 +01:00
$mailer = Mail::mailer($this->mailer);
2023-02-16 02:36:09 +01:00
if ($this->client_postmark_secret) {
2023-01-11 09:29:27 +01:00
$mailer->postmark_config($this->client_postmark_secret);
}
2023-02-16 02:36:09 +01:00
if ($this->client_mailgun_secret) {
2023-03-24 03:08:28 +01:00
$mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain, $this->nmo->settings->mailgun_endpoint);
2023-01-11 09:29:27 +01:00
}
2023-12-18 19:37:13 +01:00
if ($this->client_brevo_secret) {
2023-12-21 16:59:39 +01:00
$mailer->brevo_config($this->client_brevo_secret);
2023-12-18 19:37:13 +01:00
}
$mailable = $this->nmo->mailable;
2024-02-13 05:25:18 +01:00
2024-05-21 03:40:12 +02:00
/** May need to re-build it here @todo explain why we need this? */
if (Ninja::isHosted() && method_exists($mailable, 'build') && $this->nmo->settings->email_style != "custom") {
$mailable->build();
}
$mailer
->to($this->nmo->to_user->email)
->send($mailable);
2021-04-25 00:18:35 +02:00
2021-08-07 11:32:31 +02:00
/* Count the amount of emails sent across all the users accounts */
2024-03-13 10:19:17 +01:00
$this->incrementEmailCounter();
2021-07-23 11:38:30 +02:00
2023-11-11 00:57:46 +01:00
LightLogs::create(new EmailSuccess($this->nmo->company->company_key, $this->nmo->mailable->subject))
2023-12-18 19:37:13 +01:00
->send();
2023-12-18 19:37:13 +01:00
} catch (\Symfony\Component\Mime\Exception\RfcComplianceException $e) {
2023-02-16 02:36:09 +01:00
nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
$this->fail();
$this->cleanUpMailers();
$this->logMailError($e->getMessage(), $this->company->clients()->first());
return;
2023-12-18 19:37:13 +01:00
} catch (\Symfony\Component\Mime\Exception\LogicException $e) {
2023-02-16 02:36:09 +01:00
nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
$this->fail();
$this->cleanUpMailers();
$this->logMailError($e->getMessage(), $this->company->clients()->first());
return;
} catch (\Exception | \Google\Service\Exception $e) {
nlog("Mailer failed with {$e->getMessage()}");
2021-09-06 05:07:11 +02:00
$message = $e->getMessage();
2021-09-08 03:04:50 +02:00
/**
* Post mark buries the proper message in a a guzzle response
* this merges a text string with a json object
* need to harvest the ->Message property using the following
*/
2023-11-18 06:45:00 +01:00
if (stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) {
$message = "Either Attachment too large, or recipient has been suppressed.";
$this->fail();
$this->logMailError($e->getMessage(), $this->company->clients()->first());
2024-04-03 08:37:21 +02:00
if ($this->nmo->entity) {
$this->entityEmailFailed($message);
}
$this->cleanUpMailers();
return;
2021-09-06 05:07:11 +02:00
}
2023-11-18 06:45:00 +01:00
if (stripos($e->getMessage(), 'code 406')) {
$email = $this->nmo->to_user->email ?? '';
$message = "Recipient {$email} has been suppressed and cannot receive emails from you.";
$this->fail();
$this->logMailError($message, $this->company->clients()->first());
2024-04-03 08:37:21 +02:00
if ($this->nmo->entity) {
$this->entityEmailFailed($message);
}
2023-11-18 06:45:00 +01:00
$this->cleanUpMailers();
return;
}
//only report once, not on all tries
2023-02-16 02:36:09 +01:00
if ($this->attempts() == $this->tries) {
2024-04-03 08:37:21 +02:00
/* If there is an entity attached to the message send a failure mailer */
2023-02-16 02:36:09 +01:00
if ($this->nmo->entity) {
$this->entityEmailFailed($message);
2023-02-16 02:36:09 +01:00
}
2022-11-01 11:20:28 +01:00
/* Don't send postmark failures to Sentry */
2023-02-16 02:36:09 +01:00
if (Ninja::isHosted() && (!$e instanceof ClientException)) {
app('sentry')->captureException($e);
2023-02-16 02:36:09 +01:00
}
}
2024-01-14 05:05:00 +01:00
2023-01-29 08:29:35 +01:00
/* Releasing immediately does not add in the backoff */
2024-04-19 02:32:16 +02:00
sleep(rand(5, 10));
2024-01-14 05:05:00 +01:00
$this->release($this->backoff()[$this->attempts() - 1]);
2023-01-29 08:29:35 +01:00
}
2023-08-19 08:44:17 +02:00
$this->nmo = null;
$this->company = null;
2023-02-16 02:36:09 +01:00
/*Clean up mailers*/
2023-01-11 09:29:27 +01:00
$this->cleanUpMailers();
2021-02-16 13:56:12 +01:00
}
2024-03-13 10:19:17 +01:00
private function incrementEmailCounter(): void
{
2024-03-17 05:25:31 +01:00
if(in_array($this->mailer, ['default','mailgun','postmark']))
2024-03-13 10:19:17 +01:00
Cache::increment("email_quota".$this->company->account->key);
}
2023-01-11 09:29:27 +01:00
/**
* Entity notification when an email fails to send
2023-02-16 02:36:09 +01:00
*
2023-01-11 09:29:27 +01:00
* @param string $message
* @return void
*/
private function entityEmailFailed($message): void
2021-02-16 13:56:12 +01:00
{
2021-02-18 00:30:31 +01:00
$class = get_class($this->nmo->entity);
switch ($class) {
case Invoice::class:
2023-02-17 22:06:53 +01:00
event(new InvoiceWasEmailedAndFailed($this->nmo->invitation, $this->nmo->company, $message, $this->nmo->template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
2021-02-16 13:56:12 +01:00
break;
2021-02-18 00:30:31 +01:00
case Payment::class:
2021-04-14 07:28:05 +02:00
event(new PaymentWasEmailedAndFailed($this->nmo->entity, $this->nmo->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
2021-02-18 00:30:31 +01:00
break;
2021-02-16 13:56:12 +01:00
default:
# code...
break;
2021-02-14 11:43:44 +01:00
}
2021-02-18 00:30:31 +01:00
2023-02-16 02:36:09 +01:00
if ($this->nmo->to_user instanceof ClientContact) {
2021-02-18 01:12:49 +01:00
$this->logMailError($message, $this->nmo->to_user->client);
2023-02-16 02:36:09 +01:00
}
2021-02-14 11:43:44 +01:00
}
2023-01-11 09:29:27 +01:00
/**
* Initializes the configured Mailer
*/
2021-02-14 11:43:44 +01:00
private function setMailDriver()
{
/* Singletons need to be rebooted each time just in case our Locale is changing*/
App::forgetInstance('translator');
2021-05-31 12:40:34 +02:00
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->nmo->settings));
2021-02-14 11:43:44 +01:00
2024-01-27 05:43:37 +01:00
/** Force free/trials onto specific mail driver */
2024-02-06 21:42:46 +01:00
// if(Ninja::isHosted() && !$this->company->account->isPaid())
// {
// $this->mailer = 'mailgun';
// $this->setHostedMailgunMailer();
// return $this;
// }
2024-03-17 08:43:40 +01:00
if (Ninja::isHosted() && $this->company->account->isPaid() && $this->nmo->settings->email_sending_method == 'default') {
2024-02-06 21:42:46 +01:00
//check if outlook.
2024-02-13 05:25:18 +01:00
try {
2024-02-06 21:42:46 +01:00
$email = $this->nmo->to_user->email;
$domain = explode("@", $email)[1] ?? "";
$dns = dns_get_record($domain, DNS_MX);
$server = $dns[0]["target"];
2024-03-17 08:43:40 +01:00
if (stripos($server, "outlook.com") !== false) {
2024-02-13 05:25:18 +01:00
2024-02-06 21:42:46 +01:00
$this->mailer = 'postmark';
$this->client_postmark_secret = config('services.postmark-outlook.token');
2024-03-05 06:06:02 +01:00
if (property_exists($this->nmo->settings, 'email_from_name') && strlen($this->nmo->settings->email_from_name) > 1) {
$email_from_name = $this->nmo->settings->email_from_name;
} else {
$email_from_name = $this->company->present()->name();
}
2024-02-06 21:42:46 +01:00
$this->nmo
2024-03-17 08:43:40 +01:00
->mailable
->from(config('services.postmark-outlook.from.address'), $email_from_name);
2024-02-06 21:42:46 +01:00
return $this;
}
2024-03-17 08:43:40 +01:00
} catch (\Exception $e) {
nlog("problem switching outlook driver - hosted");
2024-02-06 21:42:46 +01:00
nlog($e->getMessage());
}
2024-01-27 05:43:37 +01:00
}
2021-02-14 11:43:44 +01:00
switch ($this->nmo->settings->email_sending_method) {
case 'default':
2021-06-17 09:48:23 +02:00
$this->mailer = config('mail.default');
2024-01-16 22:44:39 +01:00
// $this->setHostedMailgunMailer(); //should only be activated if hosted platform needs to fall back to mailgun
2024-01-27 05:43:37 +01:00
return $this;
case 'mailgun':
$this->mailer = 'mailgun';
2024-01-16 22:44:39 +01:00
$this->setHostedMailgunMailer();
2024-01-27 05:43:37 +01:00
return $this;
2021-02-14 11:43:44 +01:00
case 'gmail':
2021-06-17 09:48:23 +02:00
$this->mailer = 'gmail';
2021-02-14 11:43:44 +01:00
$this->setGmailMailer();
2023-06-30 06:34:24 +02:00
return $this;
2022-06-17 10:28:31 +02:00
case 'office365':
2023-06-30 06:50:20 +02:00
case 'microsoft':
2022-06-17 10:28:31 +02:00
$this->mailer = 'office365';
$this->setOfficeMailer();
2023-06-30 06:34:24 +02:00
return $this;
2023-01-11 09:29:27 +01:00
case 'client_postmark':
$this->mailer = 'postmark';
$this->setPostmarkMailer();
2023-06-30 06:34:24 +02:00
return $this;
2023-01-11 09:29:27 +01:00
case 'client_mailgun':
$this->mailer = 'mailgun';
$this->setMailgunMailer();
2023-06-30 06:34:24 +02:00
return $this;
2024-03-17 08:43:40 +01:00
case 'client_brevo':
$this->mailer = 'brevo';
$this->setBrevoMailer();
return $this;
case 'smtp':
$this->mailer = 'smtp';
$this->configureSmtpMailer();
return $this;
2021-02-14 11:43:44 +01:00
default:
break;
}
2021-02-17 01:25:30 +01:00
2023-02-16 02:36:09 +01:00
if (Ninja::isSelfHost()) {
2022-11-02 07:30:55 +01:00
$this->setSelfHostMultiMailer();
2023-02-16 02:36:09 +01:00
}
2023-06-30 06:34:24 +02:00
return $this;
2021-02-14 11:43:44 +01:00
}
private function configureSmtpMailer()
{
$company = $this->company;
$smtp_host = $company->smtp_host;
$smtp_port = $company->smtp_port;
$smtp_username = $company->smtp_username;
$smtp_password = $company->smtp_password;
$smtp_encryption = $company->smtp_encryption ?? 'tls';
$smtp_local_domain = strlen($company->smtp_local_domain) > 2 ? $company->smtp_local_domain : null;
$smtp_verify_peer = $company->smtp_verify_peer ?? true;
if(strlen($smtp_host ?? '') <= 1 ||
strlen($smtp_username ?? '') <= 1 ||
strlen($smtp_password ?? '') <= 1
)
{
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
config([
'mail.mailers.smtp' => [
'transport' => 'smtp',
'host' => $smtp_host,
'port' => $smtp_port,
'username' => $smtp_username,
'password' => $smtp_password,
'encryption' => $smtp_encryption,
'local_domain' => $smtp_local_domain,
'verify_peer' => $smtp_verify_peer,
'timeout' => 30,
],
]);
if (property_exists($this->nmo->settings, 'email_from_name') && strlen($this->nmo->settings->email_from_name) > 1) {
$email_from_name = $this->nmo->settings->email_from_name;
} else {
$email_from_name = $this->company->present()->name();
}
$user = $this->resolveSendingUser();
2024-03-17 08:43:40 +01:00
$sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email;
$this->nmo
2024-03-17 08:43:40 +01:00
->mailable
->from($sending_email, $email_from_name);
}
2023-01-11 09:29:27 +01:00
/**
* Allows configuration of multiple mailers
* per company for use by self hosted users
*/
private function setSelfHostMultiMailer(): void
2022-11-02 07:30:55 +01:00
{
2023-02-16 02:36:09 +01:00
if (env($this->company->id . '_MAIL_HOST')) {
2022-11-02 07:30:55 +01:00
config([
'mail.mailers.smtp' => [
'transport' => 'smtp',
'host' => env($this->company->id . '_MAIL_HOST'),
'port' => env($this->company->id . '_MAIL_PORT'),
'username' => env($this->company->id . '_MAIL_USERNAME'),
'password' => env($this->company->id . '_MAIL_PASSWORD'),
],
]);
2023-02-16 02:36:09 +01:00
if (env($this->company->id . '_MAIL_FROM_ADDRESS')) {
$this->nmo
2023-12-18 19:37:13 +01:00
->mailable
->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
2023-02-16 02:36:09 +01:00
}
2022-11-02 07:30:55 +01:00
}
}
2023-01-11 09:29:27 +01:00
/**
* Ensure we discard any data that is not required
2023-02-16 02:36:09 +01:00
*
2023-01-11 09:29:27 +01:00
* @return void
*/
private function cleanUpMailers(): void
{
$this->client_postmark_secret = false;
2022-11-02 07:30:55 +01:00
2023-01-11 09:29:27 +01:00
$this->client_mailgun_secret = false;
$this->client_mailgun_domain = false;
2023-12-18 19:37:13 +01:00
$this->client_brevo_secret = false;
2023-02-16 02:36:09 +01:00
//always dump the drivers to prevent reuse
2023-01-11 09:29:27 +01:00
app('mail.manager')->forgetMailers();
}
2023-02-16 02:36:09 +01:00
/**
2023-01-11 09:29:27 +01:00
* Check to ensure no cross account
* emails can be sent.
2023-02-16 02:36:09 +01:00
*
2023-01-11 09:29:27 +01:00
* @param User $user
*/
private function checkValidSendingUser($user)
{
/* Always ensure the user is set on the correct account */
2023-02-16 02:36:09 +01:00
if ($user->account_id != $this->company->account_id) {
2023-01-11 09:29:27 +01:00
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
}
/**
* Resolves the sending user
* when configuring the Mailer
* on behalf of the client
2023-02-16 02:36:09 +01:00
*
2023-01-11 09:29:27 +01:00
* @return User $user
*/
private function resolveSendingUser(): ?User
2022-06-17 10:28:31 +02:00
{
$sending_user = $this->nmo->settings->gmail_sending_user_id;
2023-02-16 02:36:09 +01:00
if ($sending_user == "0") {
2023-01-15 05:36:00 +01:00
$user = $this->company->owner();
2023-02-16 02:36:09 +01:00
} else {
2023-01-15 05:36:00 +01:00
$user = User::find($this->decodePrimaryKey($sending_user));
2023-02-16 02:36:09 +01:00
}
2022-06-27 08:37:18 +02:00
2023-01-11 09:29:27 +01:00
return $user;
}
2024-01-16 22:44:39 +01:00
private function setHostedMailgunMailer()
{
2024-02-13 05:25:18 +01:00
2024-01-16 22:44:39 +01:00
if (property_exists($this->nmo->settings, 'email_from_name') && strlen($this->nmo->settings->email_from_name) > 1) {
$email_from_name = $this->nmo->settings->email_from_name;
} else {
$email_from_name = $this->company->present()->name();
}
$this->nmo
->mailable
->from(config('services.mailgun.from.address'), $email_from_name);
2024-01-16 22:44:39 +01:00
}
2023-01-11 09:29:27 +01:00
/**
* Configures Mailgun using client supplied secret
* as the Mailer
*/
private function setMailgunMailer()
{
2023-02-16 02:36:09 +01:00
if (strlen($this->nmo->settings->mailgun_secret) > 2 && strlen($this->nmo->settings->mailgun_domain) > 2) {
2023-01-11 09:29:27 +01:00
$this->client_mailgun_secret = $this->nmo->settings->mailgun_secret;
$this->client_mailgun_domain = $this->nmo->settings->mailgun_domain;
2023-02-16 02:36:09 +01:00
} else {
2022-06-27 08:37:18 +02:00
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
2023-01-11 09:29:27 +01:00
}
$user = $this->resolveSendingUser();
2024-03-17 08:43:40 +01:00
$sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email;
$sending_user = (isset ($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name();
2023-02-16 02:36:09 +01:00
$this->nmo
2023-12-18 19:37:13 +01:00
->mailable
->from($sending_email, $sending_user);
}
/**
* Configures Brevo using client supplied secret
* as the Mailer
*/
private function setBrevoMailer()
{
2023-12-21 16:59:39 +01:00
if (strlen($this->nmo->settings->brevo_secret) > 2) {
2023-12-18 19:37:13 +01:00
$this->client_brevo_secret = $this->nmo->settings->brevo_secret;
} else {
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$user = $this->resolveSendingUser();
2024-03-17 08:43:40 +01:00
$sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email;
$sending_user = (isset ($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name();
2023-12-18 19:37:13 +01:00
$this->nmo
->mailable
->from($sending_email, $sending_user);
2023-01-11 09:29:27 +01:00
}
2022-06-27 08:37:18 +02:00
2023-01-11 09:29:27 +01:00
/**
* Configures Postmark using client supplied secret
* as the Mailer
*/
private function setPostmarkMailer()
2023-02-15 13:09:27 +01:00
{
2023-02-16 02:36:09 +01:00
if (strlen($this->nmo->settings->postmark_secret) > 2) {
2023-01-11 09:29:27 +01:00
$this->client_postmark_secret = $this->nmo->settings->postmark_secret;
2023-02-16 02:36:09 +01:00
} else {
2023-01-11 09:29:27 +01:00
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
2022-06-27 08:37:18 +02:00
}
2023-01-11 09:29:27 +01:00
$user = $this->resolveSendingUser();
2024-03-17 08:43:40 +01:00
$sending_email = (isset ($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email;
$sending_user = (isset ($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name();
2023-02-15 13:09:27 +01:00
2023-02-16 02:36:09 +01:00
$this->nmo
2023-12-18 19:37:13 +01:00
->mailable
->from($sending_email, $sending_user);
2023-01-11 09:29:27 +01:00
}
/**
* Configures Microsoft via Oauth
* as the Mailer
*/
private function setOfficeMailer()
{
$user = $this->resolveSendingUser();
$this->checkValidSendingUser($user);
2024-01-14 05:05:00 +01:00
2022-06-17 10:28:31 +02:00
nlog("Sending via {$user->name()}");
2022-06-17 10:37:45 +02:00
$token = $this->refreshOfficeToken($user);
2023-02-16 02:36:09 +01:00
if ($token) {
2022-06-17 10:37:45 +02:00
$user->oauth_user_token = $token;
$user->save();
2023-02-16 02:36:09 +01:00
} else {
2022-06-17 10:37:45 +02:00
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
2022-06-17 10:28:31 +02:00
$this->nmo
2023-12-18 19:37:13 +01:00
->mailable
->from($user->email, $user->name())
->withSymfonyMessage(function ($message) use ($token) {
$message->getHeaders()->addTextHeader('gmailtoken', $token);
});
2022-06-17 10:28:31 +02:00
}
2023-01-11 09:29:27 +01:00
/**
* Configures GMail via Oauth
* as the Mailer
*/
2021-02-14 11:43:44 +01:00
private function setGmailMailer()
{
2023-01-11 09:29:27 +01:00
$user = $this->resolveSendingUser();
2021-02-14 11:43:44 +01:00
2023-01-11 09:29:27 +01:00
$this->checkValidSendingUser($user);
2021-02-14 11:43:44 +01:00
2021-02-22 10:54:46 +01:00
nlog("Sending via {$user->name()}");
2021-02-16 12:19:07 +01:00
2021-02-14 11:43:44 +01:00
$google = (new Google())->init();
2023-02-16 02:36:09 +01:00
try {
if ($google->getClient()->isAccessTokenExpired()) {
$google->refreshToken($user);
$user = $user->fresh();
}
$google->getClient()->setAccessToken(json_encode($user->oauth_user_token));
2023-12-18 19:37:13 +01:00
} catch (\Exception $e) {
$this->logMailError('Gmail Token Invalid', $this->company->clients()->first());
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
2021-02-14 11:43:44 +01:00
2022-03-23 22:34:52 +01:00
/**
* If the user doesn't have a valid token, notify them
*/
2023-02-16 02:36:09 +01:00
if (!$user->oauth_user_token) {
2022-03-23 22:34:52 +01:00
$this->company->account->gmailCredentialNotification();
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
2022-03-23 22:34:52 +01:00
}
2021-02-14 11:43:44 +01:00
/*
* Now that our token is refreshed and valid we can boot the
* mail driver at runtime and also set the token which will persist
* just for this request.
2023-12-18 19:37:13 +01:00
*/
2021-02-14 11:43:44 +01:00
$token = $user->oauth_user_token->access_token;
2021-02-17 01:25:30 +01:00
2023-02-16 02:36:09 +01:00
if (!$token) {
$this->company->account->gmailCredentialNotification();
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$this->nmo
2023-12-18 19:37:13 +01:00
->mailable
->from($user->email, $user->name())
->withSymfonyMessage(function ($message) use ($token) {
$message->getHeaders()->addTextHeader('gmailtoken', $token);
});
2021-02-14 11:43:44 +01:00
}
2023-01-11 09:29:27 +01:00
/**
2023-02-16 02:36:09 +01:00
* On the hosted platform we scan all outbound email for
2023-01-11 09:29:27 +01:00
* spam. This sequence processes the filters we use on all
* emails.
2023-02-16 02:36:09 +01:00
*
2023-01-11 09:29:27 +01:00
* @return bool
*/
private function preFlightChecksFail(): bool
2021-06-29 22:23:23 +02:00
{
2023-10-26 04:57:44 +02:00
/* Always send regardless */
2023-12-18 19:37:13 +01:00
if ($this->override) {
2023-04-22 07:18:53 +02:00
return false;
}
2021-06-29 22:23:23 +02:00
/* If we are migrating data we don't want to fire any emails */
2023-04-22 07:18:53 +02:00
if ($this->company->is_disabled) {
2021-06-29 22:23:23 +02:00
return true;
2023-02-16 02:36:09 +01:00
}
2021-06-29 22:23:23 +02:00
2022-08-19 04:09:50 +02:00
/* To handle spam users we drop all emails from flagged accounts */
2023-02-16 02:36:09 +01:00
if (Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) {
2022-08-19 04:09:50 +02:00
return true;
2023-02-16 02:36:09 +01:00
}
2022-08-19 04:09:50 +02:00
2021-06-29 22:23:23 +02:00
/* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */
2023-02-16 02:36:09 +01:00
if (Ninja::isHosted() && $this->nmo->to_user && strpos($this->nmo->to_user->email, '@example.com') !== false) {
2021-06-29 22:23:23 +02:00
return true;
2023-02-16 02:36:09 +01:00
}
2021-06-29 22:23:23 +02:00
2021-08-09 12:33:59 +02:00
/* GMail users are uncapped */
2023-12-18 19:37:13 +01:00
if (Ninja::isHosted() && (in_array($this->nmo->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun', 'client_brevo']))) {
2021-08-09 12:33:59 +02:00
return false;
2023-02-16 02:36:09 +01:00
}
2021-08-09 12:33:59 +02:00
2022-08-19 02:36:13 +02:00
/* On the hosted platform, if the user is over the email quotas, we do not send the email. */
2023-02-16 02:36:09 +01:00
if (Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) {
2022-08-19 02:36:13 +02:00
return true;
2023-02-16 02:36:09 +01:00
}
2022-08-19 02:36:13 +02:00
2022-07-23 01:19:06 +02:00
/* If the account is verified, we allow emails to flow */
2023-02-16 02:36:09 +01:00
if (Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) {
2022-07-23 01:19:06 +02:00
return false;
2022-07-24 09:44:40 +02:00
}
2022-07-23 01:19:06 +02:00
/* Ensure the user has a valid email address */
2023-02-16 02:36:09 +01:00
if (!str_contains($this->nmo->to_user->email, "@")) {
return true;
2023-02-16 02:36:09 +01:00
}
2024-01-14 05:05:00 +01:00
2022-08-31 06:30:23 +02:00
/* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */
2023-02-16 02:36:09 +01:00
if (Ninja::isHosted() && $this->company->account && !$this->company->account->account_sms_verified) {
if (class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) {
2023-12-16 04:23:07 +01:00
(new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
2023-02-16 02:36:09 +01:00
}
return true;
2022-08-31 06:30:23 +02:00
}
2022-08-31 04:05:15 +02:00
/* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */
2023-02-16 02:36:09 +01:00
if (class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) {
2022-08-31 04:05:15 +02:00
return (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
2023-02-16 02:36:09 +01:00
}
2021-06-29 22:23:23 +02:00
return false;
}
2023-01-11 09:29:27 +01:00
/**
* Logs any errors to the SystemLog
2023-02-16 02:36:09 +01:00
*
2023-01-11 09:29:27 +01:00
* @param string $errors
2023-08-08 10:56:31 +02:00
* @param \App\Models\User | \App\Models\Client | null $recipient_object
2023-01-11 09:29:27 +01:00
* @return void
*/
2024-01-14 05:05:00 +01:00
private function logMailError($errors, $recipient_object): void
2021-02-14 11:43:44 +01:00
{
(
new SystemLogger(
$errors,
SystemLog::CATEGORY_MAIL,
SystemLog::EVENT_MAIL_SEND,
SystemLog::TYPE_FAILURE,
$recipient_object,
$this->nmo->company
)
)->handle();
2021-02-14 11:43:44 +01:00
2021-04-24 15:19:46 +02:00
$job_failure = new EmailFailure($this->nmo->company->company_key);
2021-04-25 06:36:22 +02:00
$job_failure->string_metric5 = 'failed_email';
2021-09-06 05:07:11 +02:00
$job_failure->string_metric6 = substr($errors, 0, 150);
2021-02-14 11:43:44 +01:00
LightLogs::create($job_failure)
2023-12-18 19:37:13 +01:00
->send();
2022-11-01 07:10:05 +01:00
$job_failure = null;
2021-02-14 11:43:44 +01:00
}
2021-08-07 11:32:31 +02:00
2023-01-11 09:29:27 +01:00
/**
* Attempts to refresh the Microsoft refreshToken
2023-02-16 02:36:09 +01:00
*
2023-04-27 00:05:57 +02:00
* @param \App\Models\User $user
* @return mixed
2023-01-11 09:29:27 +01:00
*/
2023-04-27 00:05:57 +02:00
private function refreshOfficeToken(User $user)
2022-06-17 10:37:45 +02:00
{
2022-06-22 11:18:00 +02:00
$expiry = $user->oauth_user_token_expiry ?: now()->subDay();
2022-06-17 10:37:45 +02:00
2023-02-16 02:36:09 +01:00
if ($expiry->lt(now())) {
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
2022-06-22 11:15:31 +02:00
2023-03-18 08:24:56 +01:00
if (!$user->oauth_user_refresh_token || $user->oauth_user_refresh_token == '') {
return false;
2023-03-18 08:24:56 +01:00
}
2022-06-22 11:15:31 +02:00
$token = json_decode($guzzle->post($url, [
'form_params' => [
2023-12-18 19:37:13 +01:00
'client_id' => config('ninja.o365.client_id'),
'client_secret' => config('ninja.o365.client_secret'),
'scope' => 'email Mail.Send offline_access profile User.Read openid',
2022-06-22 11:15:31 +02:00
'grant_type' => 'refresh_token',
'refresh_token' => $user->oauth_user_refresh_token
],
])->getBody()->getContents());
2024-01-14 05:05:00 +01:00
2023-02-16 02:36:09 +01:00
if ($token) {
2022-06-22 11:21:58 +02:00
$user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token;
2022-06-22 11:15:31 +02:00
$user->oauth_user_token = $token->access_token;
$user->oauth_user_token_expiry = now()->addSeconds($token->expires_in);
$user->save();
return $token->access_token;
}
return false;
}
2022-07-03 07:52:13 +02:00
return $user->oauth_user_token;
2022-06-17 10:37:45 +02:00
}
2023-01-11 09:29:27 +01:00
public function failed($exception = null)
{
2023-02-22 07:37:16 +01:00
if ($exception) {
2023-02-19 00:45:49 +01:00
nlog($exception->getMessage());
2023-02-22 07:37:16 +01:00
}
2023-02-19 00:45:49 +01:00
config(['queue.failed.driver' => null]);
2023-01-11 09:29:27 +01:00
}
2023-02-16 02:36:09 +01:00
}