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

1006 lines
34 KiB
PHP
Raw Normal View History

2023-03-06 09:07:25 +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)
2023-03-06 09:07:25 +01:00
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Services\Email;
2023-03-18 08:24:56 +01:00
use App\DataMapper\Analytics\EmailFailure;
use App\DataMapper\Analytics\EmailSuccess;
use App\Events\Invoice\InvoiceWasEmailedAndFailed;
use App\Events\Payment\PaymentWasEmailedAndFailed;
use App\Jobs\Util\SystemLogger;
use App\Libraries\Google\Google;
use App\Libraries\MultiDB;
2024-01-14 05:05:00 +01:00
use App\Mail\Engine\PaymentEmailEngine;
2023-03-06 09:07:25 +01:00
use App\Models\Client;
2023-03-18 08:24:56 +01:00
use App\Models\ClientContact;
2023-03-06 09:07:25 +01:00
use App\Models\Company;
2023-03-08 21:20:19 +01:00
use App\Models\Invoice;
use App\Models\Payment;
2023-03-06 09:07:25 +01:00
use App\Models\SystemLog;
2023-03-18 08:24:56 +01:00
use App\Models\User;
use App\Models\Vendor;
2023-03-13 08:04:24 +01:00
use App\Models\VendorContact;
2023-03-18 08:24:56 +01:00
use App\Utils\HtmlEngine;
use App\Utils\Ninja;
2023-03-06 09:07:25 +01:00
use App\Utils\Traits\MakesHash;
2023-03-07 12:36:50 +01:00
use App\Utils\VendorHtmlEngine;
use GuzzleHttp\Exception\ClientException;
2023-03-18 08:24:56 +01:00
use Illuminate\Bus\Queueable;
2023-03-06 09:07:25 +01:00
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
2023-03-18 08:24:56 +01:00
use Illuminate\Mail\Mailable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
2023-12-21 16:59:39 +01:00
use Log;
2023-03-18 08:24:56 +01:00
use Turbo124\Beacon\Facades\LightLogs;
2023-03-06 09:07:25 +01:00
class Email implements ShouldQueue
{
2024-01-14 05:05:00 +01:00
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
use MakesHash;
2023-03-06 09:07:25 +01:00
2024-01-14 05:05:00 +01:00
/** number of retry attempts to send the emails */
2023-03-18 08:24:56 +01:00
public $tries = 4;
2023-03-06 09:07:25 +01:00
2024-01-14 05:05:00 +01:00
/** skip when we cannot resolve the model */
2023-03-06 09:07:25 +01:00
public $deleteWhenMissingModels = true;
2024-01-14 05:05:00 +01:00
/** force send the email */
2023-03-06 10:14:59 +01:00
public bool $override;
2023-03-06 09:07:25 +01:00
2024-01-14 05:05:00 +01:00
/** PostMark api key */
2023-03-06 10:14:59 +01:00
protected ?string $client_postmark_secret = null;
2023-03-06 09:07:25 +01:00
2024-01-14 05:05:00 +01:00
/** MailGun api key */
2023-03-06 10:14:59 +01:00
protected ?string $client_mailgun_secret = null;
2023-03-06 09:07:25 +01:00
2024-01-14 05:05:00 +01:00
/** MailGun domain */
2023-03-06 10:14:59 +01:00
protected ?string $client_mailgun_domain = null;
2023-03-06 09:07:25 +01:00
2024-01-14 05:05:00 +01:00
/** MailGun endpoint */
2023-03-24 03:08:28 +01:00
protected ?string $client_mailgun_endpoint = null;
/** Brevo endpoint */
2023-12-18 19:37:13 +01:00
protected ?string $client_brevo_secret = null;
2024-01-14 05:05:00 +01:00
/** Default mailer */
2023-03-06 10:14:59 +01:00
private string $mailer = 'default';
2023-03-06 09:07:25 +01:00
2024-01-14 05:05:00 +01:00
/** The mailable */
2023-03-06 10:14:59 +01:00
public Mailable $mailable;
2023-03-06 09:07:25 +01:00
public function __construct(public EmailObject $email_object, public Company $company)
{
}
2024-01-14 05:05:00 +01:00
2023-03-08 13:16:08 +01:00
/**
* The backoff time between retries.
*
* @return array
*/
2023-03-06 09:07:25 +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)];
2023-03-06 09:07:25 +01:00
}
2024-01-14 05:05:00 +01:00
/**
* Send email job.
*/
2023-03-06 09:07:25 +01:00
public function handle()
{
MultiDB::setDb($this->company->db);
$this->setOverride()
2023-12-18 19:37:13 +01:00
->initModels()
->setDefaults()
->buildMailable();
2023-03-06 10:14:59 +01:00
2023-11-01 00:34:02 +01:00
/** Ensure quota's on hosted platform are respected. :) */
$this->setMailDriver();
2024-01-14 05:05:00 +01:00
/** Fail early if pre flight checks fail. */
2023-03-18 08:24:56 +01:00
if ($this->preFlightChecksFail()) {
2023-03-06 10:14:59 +01:00
return;
2023-03-18 08:24:56 +01:00
}
2023-03-06 10:14:59 +01:00
2024-01-14 05:05:00 +01:00
/** Send the email */
2023-03-06 10:14:59 +01:00
$this->email();
2024-01-14 05:05:00 +01:00
/** Perform cleanups */
$this->tearDown();
2023-03-06 09:07:25 +01:00
}
2024-01-14 05:05:00 +01:00
2023-03-08 13:16:08 +01:00
/**
* Sets the override flag
*
* @return self
*/
2023-03-06 09:07:25 +01:00
public function setOverride(): self
{
$this->override = $this->email_object->override;
return $this;
}
2024-01-14 05:05:00 +01:00
2023-03-08 13:16:08 +01:00
/**
* Initilializes the models
*
* @return self
*/
2023-03-06 09:07:25 +01:00
public function initModels(): self
{
$this->email_object->entity_id ? $this->email_object->entity = $this->email_object->entity_class::withTrashed()->with('invitations')->find($this->email_object->entity_id) : $this->email_object->entity = null;
$this->email_object->invitation_id ? $this->email_object->invitation = $this->email_object->entity->invitations()->where('id', $this->email_object->invitation_id)->first() : $this->email_object->invitation = null;
2024-01-14 05:05:00 +01:00
$this->email_object->invitation_id ? $this->email_object->contact = $this->email_object->invitation->contact : $this->email_object->contact = null;
2023-03-06 09:07:25 +01:00
2023-03-07 12:36:50 +01:00
$this->email_object->client_id ? $this->email_object->client = Client::withTrashed()->find($this->email_object->client_id) : $this->email_object->client = null;
2024-01-14 05:05:00 +01:00
2023-03-06 09:07:25 +01:00
$this->email_object->vendor_id ? $this->email_object->vendor = Vendor::withTrashed()->find($this->email_object->vendor_id) : $this->email_object->vendor = null;
2024-01-14 05:05:00 +01:00
2023-03-18 08:24:56 +01:00
if (!$this->email_object->contact) {
2024-01-14 05:05:00 +01:00
$this->email_object->vendor_contact_id ? $this->email_object->contact = VendorContact::withTrashed()->find($this->email_object->vendor_contact_id) : null;
2023-03-07 12:36:50 +01:00
2024-01-14 05:05:00 +01:00
$this->email_object->client_contact_id ? $this->email_object->contact = ClientContact::withTrashed()->find($this->email_object->client_contact_id) : null;
2023-03-07 12:36:50 +01:00
}
2023-03-07 13:17:03 +01:00
2024-01-14 05:05:00 +01:00
$this->email_object->user_id ? $this->email_object->user = User::withTrashed()->find($this->email_object->user_id) : $this->email_object->user = $this->company->owner();
2023-03-06 09:07:25 +01:00
$this->email_object->company_key = $this->company->company_key;
$this->email_object->company = $this->company;
2023-08-18 13:36:50 +02:00
$this->email_object->client_id ? $this->email_object->settings = $this->email_object->client->getMergedSettings() : $this->email_object->settings = $this->company->settings;
2023-03-06 09:07:25 +01:00
$this->email_object->whitelabel = $this->company->account->isPaid() ? true : false;
$this->email_object->logo = $this->email_object->settings->company_logo;
$this->email_object->signature = $this->email_object->settings->email_signature;
2023-03-24 00:10:35 +01:00
$this->email_object->invitation_key = $this->email_object->invitation ? $this->email_object->invitation->key : null;
2024-01-14 05:05:00 +01:00
2023-03-07 12:36:50 +01:00
$this->resolveVariables();
return $this;
}
2024-01-14 05:05:00 +01:00
2023-03-08 13:16:08 +01:00
/**
* Generates the correct set of variables
2024-01-14 05:05:00 +01:00
*
2023-03-08 13:16:08 +01:00
* @return self
*/
2023-03-07 12:36:50 +01:00
private function resolveVariables(): self
{
2023-03-08 13:16:08 +01:00
$_variables = $this->email_object->variables;
2024-01-14 05:05:00 +01:00
2023-03-18 08:24:56 +01:00
match (class_basename($this->email_object->entity)) {
2023-03-07 13:17:03 +01:00
"Invoice" => $this->email_object->variables = (new HtmlEngine($this->email_object->invitation))->makeValues(),
"Quote" => $this->email_object->variables = (new HtmlEngine($this->email_object->invitation))->makeValues(),
"Credit" => $this->email_object->variables = (new HtmlEngine($this->email_object->invitation))->makeValues(),
"PurchaseOrder" => $this->email_object->variables = (new VendorHtmlEngine($this->email_object->invitation))->makeValues(),
2024-01-14 05:05:00 +01:00
"Payment" => $this->email_object->variables = (new PaymentEmailEngine($this->email_object->entity, $this->email_object->contact))->makePaymentVariables(),
2023-03-07 13:17:03 +01:00
default => $this->email_object->variables = []
2023-03-07 12:36:50 +01:00
};
2023-03-08 13:16:08 +01:00
/** If we have passed some variable overrides we insert them here */
2023-03-18 08:24:56 +01:00
foreach ($_variables as $key => $value) {
2023-03-08 13:16:08 +01:00
$this->email_object->variables[$key] = $value;
}
2023-03-06 09:07:25 +01:00
return $this;
}
2024-01-14 05:05:00 +01:00
2023-03-08 13:16:08 +01:00
/**
2024-01-14 05:05:00 +01:00
* Tear Down
2023-03-08 13:16:08 +01:00
*
* @return self
*/
private function tearDown(): self
{
$this->email_object->entity = null;
$this->email_object->invitation = null;
$this->email_object->client = null;
$this->email_object->vendor = null;
$this->email_object->user = null;
$this->email_object->contact = null;
$this->email_object->settings = null;
return $this;
}
2024-01-14 05:05:00 +01:00
2023-03-08 13:16:08 +01:00
/**
2024-01-14 05:05:00 +01:00
* Builds the email defaults,
* sets any missing props.
2023-03-08 13:16:08 +01:00
*
* @return self
*/
2023-03-06 09:07:25 +01:00
public function setDefaults(): self
{
(new EmailDefaults($this))->run();
return $this;
}
2024-01-14 05:05:00 +01:00
2023-03-08 13:16:08 +01:00
/**
* Populates the mailable
*
* @return self
*/
2023-03-06 09:07:25 +01:00
public function buildMailable(): self
{
$this->mailable = new EmailMailable($this->email_object);
2024-01-14 05:05:00 +01:00
2023-03-06 09:07:25 +01:00
return $this;
}
2024-01-14 05:05:00 +01:00
2024-03-13 10:19:17 +01:00
private function incrementEmailCounter(): void
{
2024-06-14 09:09:44 +02: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);
2024-06-14 09:09:44 +02:00
}
2024-03-13 10:19:17 +01:00
}
2023-03-08 13:16:08 +01:00
/**
* Attempts to send the email
*
* @return void
*/
2023-03-06 10:14:59 +01:00
public function email()
{
/* Init the mailer*/
$mailer = Mail::mailer($this->mailer);
2023-12-21 16:59:39 +01:00
2023-03-06 10:14:59 +01:00
/* Additional configuration if using a client third party mailer */
if ($this->client_postmark_secret) {
$mailer->postmark_config($this->client_postmark_secret);
}
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->client_mailgun_endpoint);
2023-03-06 10:14:59 +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
}
2023-03-06 10:14:59 +01:00
/* Attempt the send! */
try {
2023-12-18 19:37:13 +01:00
nlog("Using mailer => " . $this->mailer . " " . now()->toDateTimeString());
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
$mailer->send($this->mailable);
2024-03-13 10:19:17 +01:00
$this->incrementEmailCounter();
2023-03-06 10:14:59 +01:00
2023-11-11 00:59:31 +01:00
LightLogs::create(new EmailSuccess($this->company->company_key, $this->mailable->subject))
2023-12-18 19:37:13 +01:00
->send();
2023-08-22 12:42:01 +02:00
2023-12-18 19:37:13 +01:00
} catch (\Symfony\Component\Mime\Exception\RfcComplianceException $e) {
2023-03-13 08:04:24 +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-03-13 08:04:24 +01:00
nlog("Mailer failed with a Logic Exception {$e->getMessage()}");
$this->fail();
$this->cleanUpMailers();
$this->logMailError($e->getMessage(), $this->company->clients()->first());
return;
2024-06-14 09:09:44 +02:00
} catch(\Google\Service\Exception $e) {
2024-05-26 02:18:11 +02:00
if ($e->getCode() == '429') {
2024-06-14 09:09:44 +02:00
$message = "Google rate limiting triggered, we are queueing based on Gmail requirements.";
2024-05-26 02:18:11 +02:00
$this->logMailError($message, $this->company->clients()->first());
sleep(rand(1, 2));
$this->release(900);
$message = null;
}
2024-06-14 09:09:44 +02:00
} catch (\Exception | \RuntimeException $e) {
2023-03-18 08:24:56 +01:00
nlog("Mailer failed with {$e->getMessage()}");
2023-03-06 10:14:59 +01:00
$message = $e->getMessage();
2023-11-18 06:45:00 +01:00
2024-06-06 04:31:24 +02:00
if (stripos($e->getMessage(), 'code 300') !== false || stripos($e->getMessage(), 'code 413') !== false) {
2023-11-26 08:41:42 +01:00
$message = "Either Attachment too large, or recipient has been suppressed.";
2023-11-18 06:45:00 +01:00
2023-11-26 08:41:42 +01:00
$this->fail();
$this->logMailError($e->getMessage(), $this->company->clients()->first());
$this->cleanUpMailers();
2023-11-18 06:45:00 +01:00
2024-05-21 03:40:12 +02:00
$this->entityEmailFailed($message);
2024-04-03 08:37:21 +02:00
2023-11-26 08:41:42 +01:00
return;
}
2024-06-14 09:09:44 +02:00
2024-06-06 04:31:24 +02:00
if(stripos($e->getMessage(), 'Dsn') !== false) {
nlog("Incorrectly configured mail server - setting to default mail driver.");
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
2023-11-18 06:45:00 +01:00
2024-06-06 04:31:24 +02:00
if (stripos($e->getMessage(), 'code 406') !== false) {
2023-11-18 06:45:00 +01:00
$address_object = reset($this->email_object->to);
$email = $address_object->address ?? '';
2024-01-14 05:05:00 +01:00
2023-11-18 06:45:00 +01:00
$message = "Recipient {$email} has been suppressed and cannot receive emails from you.";
$this->fail();
2023-11-18 06:45:00 +01:00
$this->logMailError($message, $this->company->clients()->first());
$this->cleanUpMailers();
2024-04-03 08:37:21 +02:00
$this->entityEmailFailed($message);
return;
}
2023-03-06 10:14:59 +01:00
/**
2024-01-14 05:05:00 +01:00
* Post mark buries the proper message in a guzzle response
2023-03-06 10:14:59 +01:00
* this merges a text string with a json object
* need to harvest the ->Message property using the following
*/
if ($e instanceof ClientException) { //postmark specific failure
$response = $e->getResponse();
$message_body = json_decode($response->getBody()->getContents());
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
if ($message_body && property_exists($message_body, 'Message')) {
$message = $message_body->Message;
}
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
$this->fail();
2024-04-03 08:37:21 +02:00
$this->entityEmailFailed($message);
2023-03-06 10:14:59 +01:00
$this->cleanUpMailers();
2024-06-14 09:09:44 +02:00
2023-03-06 10:14:59 +01:00
return;
}
//only report once, not on all tries
if ($this->attempts() == $this->tries) {
/* If the is an entity attached to the message send a failure mailer */
$this->entityEmailFailed($message);
/* Don't send postmark failures to Sentry */
if (Ninja::isHosted() && (!$e instanceof ClientException)) {
app('sentry')->captureException($e);
}
}
$this->tearDown();
2024-01-14 05:05:00 +01:00
/* Releasing immediately does not add in the backoff */
sleep(rand(0, 3));
2024-01-14 05:05:00 +01:00
$this->release($this->backoff()[$this->attempts() - 1]);
2023-03-06 10:14:59 +01:00
$message = null;
}
$this->cleanUpMailers();
}
2023-10-26 04:57:44 +02:00
/**
2023-12-18 19:37:13 +01:00
* On the hosted platform we scan all outbound email for
* spam. This sequence processes the filters we use on all
* emails.
*
* @return bool
*/
2023-03-06 10:14:59 +01:00
public function preFlightChecksFail(): bool
{
2023-04-22 07:25:54 +02:00
/* Always send if disabled */
2023-12-18 19:37:13 +01:00
if ($this->override) {
2023-04-22 07:25:54 +02:00
return false;
}
2023-03-06 10:14:59 +01:00
/* If we are migrating data we don't want to fire any emails */
2023-04-22 07:25:54 +02:00
if ($this->company->is_disabled) {
2023-03-06 10:14:59 +01:00
return true;
}
if (Ninja::isSelfHost()) {
return false;
}
/* To handle spam users we drop all emails from flagged accounts */
if ($this->company->account && $this->company->account->is_flagged) {
return true;
}
/* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */
if ($this->hasInValidEmails()) {
return true;
}
/* GMail users are uncapped */
2023-12-21 16:59:39 +01:00
if (in_array($this->email_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun', 'client_brevo'])) {
2023-03-06 10:14:59 +01:00
return false;
}
/* On the hosted platform, if the user is over the email quotas, we do not send the email. */
if ($this->company->account && $this->company->account->emailQuotaExceeded()) {
return true;
}
/* If the account is verified, we allow emails to flow */
if ($this->company->account && $this->company->account->is_verified_account) {
//11-01-2022
/* Continue to analyse verified accounts in case they later start sending poor quality emails*/
// if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class))
// (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
return false;
}
/* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */
if ($this->company->account && !$this->company->account->account_sms_verified) {
if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) {
2023-12-16 04:23:07 +01:00
(new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run();
2023-03-06 10:14:59 +01:00
}
return true;
}
/* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */
if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) {
return (new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run();
}
return false;
}
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
/**
* hasInValidEmails
*
* @return bool
*/
private function hasInValidEmails(): bool
{
foreach ($this->email_object->to as $address_object) {
2024-01-14 05:05:00 +01:00
if (stripos($address_object->address, '@example.') !== false) {
2023-03-06 10:14:59 +01:00
return true;
}
if (!str_contains($address_object->address, "@")) {
return true;
}
if ($address_object->address == " ") {
return true;
}
2023-10-18 06:38:45 +02:00
if ($address_object->address == "") {
return true;
}
2023-12-18 19:37:13 +01:00
if ($address_object->name == " " || $address_object->name == "") {
return true;
}
2023-03-06 10:14:59 +01:00
}
return false;
}
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->email_object->settings, 'email_from_name') && strlen($this->email_object->settings->email_from_name) > 1) {
$email_from_name = $this->email_object->settings->email_from_name;
} else {
$email_from_name = $this->company->present()->name();
}
$this->mailable
->from(config('services.mailgun.from.address'), $email_from_name);
2024-01-16 22:44:39 +01:00
}
2024-02-13 05:25:18 +01:00
2023-10-26 04:57:44 +02:00
/**
2023-03-06 10:14:59 +01:00
* Sets the mail driver to use and applies any specific configuration
* the the mailable
*/
private function setMailDriver(): self
2023-03-06 09:07:25 +01:00
{
2024-01-27 05:43:37 +01:00
/** Force free/trials onto specific mail driver */
2024-07-30 08:19:07 +02:00
if($this->mailer == 'default' && $this->company->account->isNewHostedAccount()) {
$this->mailer = 'mailgun';
$this->setHostedMailgunMailer();
return $this;
}
2024-02-06 21:42:46 +01:00
if (Ninja::isHosted() && $this->company->account->isPaid() && $this->email_object->settings->email_sending_method == 'default') {
2024-02-06 21:42:46 +01:00
try {
2024-02-13 05:25:18 +01:00
2024-02-06 21:42:46 +01:00
$address_object = reset($this->email_object->to);
$email = $address_object->address ?? '';
$domain = explode("@", $email)[1] ?? "";
$dns = dns_get_record($domain, DNS_MX);
$server = $dns[0]["target"];
if (stripos($server, "outlook.com") !== false) {
2024-02-06 21:42:46 +01:00
2024-03-05 06:06:02 +01:00
if (property_exists($this->email_object->settings, 'email_from_name') && strlen($this->email_object->settings->email_from_name) > 1) {
$email_from_name = $this->email_object->settings->email_from_name;
} else {
$email_from_name = $this->company->present()->name();
}
2024-02-06 21:42:46 +01:00
$this->mailer = 'postmark';
$this->client_postmark_secret = config('services.postmark-outlook.token');
$this->mailable
->from(config('services.postmark-outlook.from.address'), $email_from_name);
2024-02-06 21:42:46 +01:00
return $this;
2024-02-06 21:42:46 +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
}
2023-03-06 10:14:59 +01:00
switch ($this->email_object->settings->email_sending_method) {
case 'default':
$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
2023-03-06 10:14:59 +01:00
break;
case 'mailgun':
$this->mailer = 'mailgun';
2024-01-16 22:44:39 +01:00
$this->setHostedMailgunMailer();
break;
2023-03-06 10:14:59 +01:00
case 'gmail':
$this->mailer = 'gmail';
$this->setGmailMailer();
return $this;
case 'office365':
2023-06-30 06:50:20 +02:00
case 'microsoft':
2023-03-06 10:14:59 +01:00
$this->mailer = 'office365';
$this->setOfficeMailer();
return $this;
case 'client_postmark':
$this->mailer = 'postmark';
$this->setPostmarkMailer();
return $this;
case 'client_mailgun':
$this->mailer = 'mailgun';
$this->setMailgunMailer();
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;
2023-03-06 10:14:59 +01:00
default:
2023-06-30 06:34:24 +02:00
$this->mailer = config('mail.default');
return $this;
2023-03-06 10:14:59 +01:00
}
if (Ninja::isSelfHost()) {
$this->setSelfHostMultiMailer();
}
2023-03-06 09:07:25 +01:00
return $this;
}
private function configureSmtpMailer()
{
$company = $this->company;
2024-06-07 02:32:10 +02:00
$smtp_host = $company->smtp_host ?? '';
$smtp_port = $company->smtp_port;
2024-06-07 02:32:10 +02:00
$smtp_username = $company->smtp_username ?? '';
$smtp_password = $company->smtp_password ?? '';
$smtp_encryption = $company->smtp_encryption ?? 'tls';
2024-07-30 08:19:07 +02:00
$smtp_local_domain = strlen($company->smtp_local_domain ?? '') > 2 ? $company->smtp_local_domain : null;
$smtp_verify_peer = $company->smtp_verify_peer ?? true;
2024-06-07 02:32:10 +02:00
if(strlen($smtp_host) <= 1 ||
strlen($smtp_username) <= 1 ||
strlen($smtp_password) <= 1
) {
$this->email_object->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,
],
]);
$user = $this->resolveSendingUser();
2024-06-14 09:09:44 +02:00
$sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name();
$this->mailable
->from($sending_email, $sending_user);
}
2023-10-26 04:57:44 +02:00
/**
2023-03-06 10:14:59 +01:00
* Allows configuration of multiple mailers
* per company for use by self hosted users
*/
private function setSelfHostMultiMailer(): void
{
if (env($this->company->id . '_MAIL_HOST')) {
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'),
],
]);
if (env($this->company->id . '_MAIL_FROM_ADDRESS')) {
$this->mailable
2023-12-18 19:37:13 +01:00
->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME')));
2023-03-06 10:14:59 +01:00
}
}
}
/**
* Ensure we discard any data that is not required
*
* @return void
*/
private function cleanUpMailers(): void
{
$this->client_postmark_secret = null;
$this->client_mailgun_secret = null;
$this->client_mailgun_domain = null;
2023-03-24 03:08:28 +01:00
$this->client_mailgun_endpoint = null;
2023-12-18 19:37:13 +01:00
$this->client_brevo_secret = null;
2023-03-06 10:14:59 +01:00
//always dump the drivers to prevent reuse
app('mail.manager')->forgetMailers();
}
/**
* Check to ensure no cross account
* emails can be sent.
*
* @param User $user
*/
private function checkValidSendingUser($user)
{
/* Always ensure the user is set on the correct account */
if ($user->account_id != $this->company->account_id) {
$this->email_object->settings->email_sending_method = 'default';
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
return $this->setMailDriver();
}
}
/**
* Resolves the sending user
* when configuring the Mailer
* on behalf of the client
*
* @return User $user
*/
private function resolveSendingUser(): ?User
{
$sending_user = $this->email_object->settings->gmail_sending_user_id;
if ($sending_user == "0") {
$user = $this->company->owner();
} else {
$user = User::find($this->decodePrimaryKey($sending_user));
}
return $user;
}
/**
* Configures Mailgun using client supplied secret
* as the Mailer
*/
private function setMailgunMailer()
{
if (strlen($this->email_object->settings->mailgun_secret) > 2 && strlen($this->email_object->settings->mailgun_domain) > 2) {
$this->client_mailgun_secret = $this->email_object->settings->mailgun_secret;
$this->client_mailgun_domain = $this->email_object->settings->mailgun_domain;
2023-03-24 03:08:28 +01:00
$this->client_mailgun_endpoint = $this->email_object->settings->mailgun_endpoint;
2023-03-06 10:14:59 +01:00
} else {
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$user = $this->resolveSendingUser();
2024-06-14 09:09:44 +02:00
$sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name();
2023-03-06 10:14:59 +01:00
$this->mailable
2023-12-18 19:37:13 +01:00
->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->email_object->settings->brevo_secret) > 2) {
2023-12-18 19:37:13 +01:00
$this->client_brevo_secret = $this->email_object->settings->brevo_secret;
} else {
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$user = $this->resolveSendingUser();
2024-06-14 09:09:44 +02:00
$sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name();
2023-12-18 19:37:13 +01:00
$this->mailable
->from($sending_email, $sending_user);
2023-03-06 10:14:59 +01:00
}
/**
* Configures Postmark using client supplied secret
* as the Mailer
*/
private function setPostmarkMailer()
{
if (strlen($this->email_object->settings->postmark_secret) > 2) {
$this->client_postmark_secret = $this->email_object->settings->postmark_secret;
} else {
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$user = $this->resolveSendingUser();
2024-06-14 09:09:44 +02:00
$sending_email = (isset($this->email_object->settings->custom_sending_email) && stripos($this->email_object->settings->custom_sending_email, "@")) ? $this->email_object->settings->custom_sending_email : $user->email;
$sending_user = (isset($this->email_object->settings->email_from_name) && strlen($this->email_object->settings->email_from_name) > 2) ? $this->email_object->settings->email_from_name : $user->name();
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
$this->mailable
2023-12-18 19:37:13 +01:00
->from($sending_email, $sending_user);
2023-03-06 10:14:59 +01:00
}
/**
* Configures Microsoft via Oauth
* as the Mailer
*/
private function setOfficeMailer()
{
$user = $this->resolveSendingUser();
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
$this->checkValidSendingUser($user);
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
nlog("Sending via {$user->name()}");
$token = $this->refreshOfficeToken($user);
if ($token) {
$user->oauth_user_token = $token;
$user->save();
} else {
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$this->mailable
2023-12-18 19:37:13 +01:00
->from($user->email, $user->name())
->withSymfonyMessage(function ($message) use ($token) {
$message->getHeaders()->addTextHeader('gmailtoken', $token);
});
2023-03-06 10:14:59 +01:00
}
/**
* Configures GMail via Oauth
* as the Mailer
*/
private function setGmailMailer()
{
$user = $this->resolveSendingUser();
$this->checkValidSendingUser($user);
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
nlog("Sending via {$user->name()}");
$google = (new Google())->init();
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) {
2023-03-06 10:14:59 +01:00
$this->logMailError('Gmail Token Invalid', $this->company->clients()->first());
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
/**
* If the user doesn't have a valid token, notify them
*/
if (!$user->oauth_user_token) {
$this->company->account->gmailCredentialNotification();
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
/*
* 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
*/
2023-03-06 10:14:59 +01:00
$token = $user->oauth_user_token->access_token;
if (!$token) {
$this->company->account->gmailCredentialNotification();
$this->email_object->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$this->mailable
2023-12-18 19:37:13 +01:00
->from($user->email, $user->name())
->withSymfonyMessage(function ($message) use ($token) {
$message->getHeaders()->addTextHeader('gmailtoken', $token);
});
2023-03-06 10:14:59 +01:00
}
/**
* Logs any errors to the SystemLog
*
* @param string $errors
2023-03-08 13:16:08 +01:00
* @param null | \App\Models\Client $recipient_object
2023-03-06 10:14:59 +01:00
* @return void
*/
2024-01-14 05:05:00 +01:00
private function logMailError($errors, $recipient_object): void
2023-03-06 09:07:25 +01:00
{
(
new SystemLogger(
$errors,
SystemLog::CATEGORY_MAIL,
SystemLog::EVENT_MAIL_SEND,
SystemLog::TYPE_FAILURE,
$recipient_object,
$this->company
)
)->handle();
2023-03-06 10:14:59 +01:00
$job_failure = new EmailFailure($this->company->company_key);
$job_failure->string_metric5 = 'failed_email';
$job_failure->string_metric6 = substr($errors, 0, 150);
LightLogs::create($job_failure)
2023-12-18 19:37:13 +01:00
->send();
2023-03-06 10:14:59 +01:00
$job_failure = null;
2023-03-06 09:07:25 +01:00
}
2023-03-06 10:14:59 +01:00
/**
* Attempts to refresh the Microsoft refreshToken
*
2023-03-08 13:16:08 +01:00
* @param \App\Models\User $user
2023-03-06 10:14:59 +01:00
* @return mixed
*/
private function refreshOfficeToken(User $user): mixed
{
$expiry = $user->oauth_user_token_expiry ?: now()->subDay();
2024-06-08 01:13:47 +02:00
$token = false;
2024-06-14 09:09:44 +02:00
2023-03-06 10:14:59 +01:00
if ($expiry->lt(now())) {
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
2024-05-26 23:26:20 +02:00
try {
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => config('ninja.o365.client_id'),
'client_secret' => config('ninja.o365.client_secret'),
'scope' => 'email Mail.Send offline_access profile User.Read openid',
'grant_type' => 'refresh_token',
'refresh_token' => $user->oauth_user_refresh_token
],
])->getBody()->getContents());
2024-06-14 09:09:44 +02:00
} catch(\Exception $e) {
2024-05-26 23:26:20 +02:00
nlog("Problem getting new Microsoft token for User: {$user->email}");
}
2024-01-14 05:05:00 +01:00
2023-03-06 10:14:59 +01:00
if ($token) {
$user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token;
$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;
}
return $user->oauth_user_token;
}
/**
* Entity notification when an email fails to send
*
* @param string $message
* @return void
*/
private function entityEmailFailed($message): void
{
$class = get_class($this->email_object->entity);
switch ($class) {
case Invoice::class:
event(new InvoiceWasEmailedAndFailed($this->email_object->invitation, $this->company, $message, $this->email_object->html_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
break;
case Payment::class:
event(new PaymentWasEmailedAndFailed($this->email_object->entity, $this->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
break;
default:
# code...
break;
}
if ($this->email_object->client) {
$this->logMailError($message, $this->email_object->client);
}
}
2023-03-06 10:14:59 +01:00
public function failed($exception = null)
{
2023-03-18 08:24:56 +01:00
if ($exception) {
2023-03-06 10:14:59 +01:00
nlog($exception->getMessage());
2023-03-18 08:24:56 +01:00
}
2023-03-06 10:14:59 +01:00
config(['queue.failed.driver' => null]);
}
2023-03-18 08:24:56 +01:00
}