-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
GmailTransport.php
95 lines (73 loc) · 2.45 KB
/
GmailTransport.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2024. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Helpers\Mail;
use Google\Client;
use Google\Service\Gmail;
use Google\Service\Gmail\Message;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\MessageConverter;
/**
* GmailTransport.
*/
class GmailTransport extends AbstractTransport
{
public function __construct()
{
parent::__construct();
}
protected function doSend(SentMessage $message): void
{
nlog("In Do Send");
$message = MessageConverter::toEmail($message->getOriginalMessage());
/** @phpstan-ignore-next-line **/
$token = $message->getHeaders()->get('gmailtoken')->getValue();
$message->getHeaders()->remove('gmailtoken');
$client = new Client();
$client->setClientId(config('ninja.auth.google.client_id'));
$client->setClientSecret(config('ninja.auth.google.client_secret'));
$client->setAccessToken($token);
$service = new Gmail($client);
$body = new Message();
$bccs = $message->getHeaders()->get('Bcc');
$bcc_list = '';
if ($bccs) {
$bcc_list = 'Bcc: ';
/** @phpstan-ignore-next-line **/
foreach ($bccs->getAddresses() as $address) {
$bcc_list .= $address->getAddress() .',';
}
$bcc_list = rtrim($bcc_list, ",") . "\r\n";
}
$body->setRaw($this->base64_encode($bcc_list.$message->toString()));
try {
$service->users_messages->send('me', $body, []);
} catch(\Google\Service\Exception $e) {
/* Need to slow down */
if ($e->getCode() == '429') {
nlog("429 google - retrying ");
sleep(rand(3,8));
try {
$service->users_messages->send('me', $body, []);
} catch(\Google\Service\Exception $e) {
}
}
}
}
private function base64_encode($data)
{
return rtrim(strtr(base64_encode($data), ['+' => '-', '/' => '_']), '=');
}
public function __toString(): string
{
return 'gmail';
}
}