-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmailBounceManagerCommand.php
226 lines (163 loc) · 7.02 KB
/
EmailBounceManagerCommand.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php
namespace App\Command;
use TurboLabIt\BaseCommand\Command\AbstractBaseCommand;
use App\Repository\PhpBB\UserRepository;
use Ddeboer\Imap\Server;
use Ddeboer\Imap\Message;
use Ddeboer\Imap\Message\Attachment;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
#[AsCommand(name: 'EmailBounceManager', description: 'Unsubscribe bouncing email addresses')]
class EmailBounceManagerCommand extends AbstractBaseCommand
{
const array MAILBOXES_TO_CHECK = ['inbox', 'spam'];
const array SUBJECT_TO_PROCESS = [
'Undelivered mail returned to sender', 'Delivery status notification',
'Undeliverable:', 'failure notice', 'Mail system error',
'Mail delivery failed', 'Rejected:'
];
const string EMAIL_ADDRESS_REGEX = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/';
protected bool $allowDryRunOpt = true;
protected array $arrMessagesToDelete = [];
protected array $arrExtractedAddresses = [];
public function __construct(
protected array $arrConfig, protected ParameterBagInterface $parameters, protected UserRepository $userRepository
)
{ parent::__construct($arrConfig); }
protected function execute(InputInterface $input, OutputInterface $output) : int
{
parent::execute($input, $output);
$this->fxTitle("Authenticating on ##" . $this->arrConfig["mailbox"]["hostname"] . "##...");
$mailserver =
(new Server($this->arrConfig["mailbox"]["hostname"]))
->authenticate($this->arrConfig["mailbox"]["username"], $this->arrConfig["mailbox"]["password"]);
$this->fxOK();
$this->fxTitle("Iterating over each mailbox...");
$mailboxes = $mailserver->getMailboxes();
foreach ($mailboxes as $mailbox) {
// Skip container-only mailboxes
// @see https://secure.php.net/manual/en/function.imap-getmailboxes.php
if( $mailbox->getAttributes() & \LATT_NOSELECT ) {
$this->fxInfo("🦘 Skipping IMAP LATT_NOSELECT");
continue;
}
$mailboxName = mb_strtolower( $mailbox->getName() );
if( !in_array($mailboxName, self::MAILBOXES_TO_CHECK) ) {
$mailboxName = mb_strtoupper( $mailbox->getName() );
$this->fxInfo("🦘 Mailbox ##$mailboxName## not whitelisted, skipped");
continue;
}
$mailboxName = mb_strtoupper( $mailbox->getName() );
$this->fxInfo("📬 Working on ##$mailboxName##");
$messages = $mailbox->getMessages();
$this->processItems($messages, [$this, 'processOneMessage'], null, [$this, 'buildItemTitle']);
}
$this->fxTitle("Post-extraction status");
$addressesNum = count($this->arrExtractedAddresses);
$this->fxOK("$addressesNum address(es) extracted");
if( $addressesNum == 0 ) {
$this->fxInfo("No address extracted. There is nothing to do");
return $this->endWithSuccess();
}
(new Table($output))
->setRows( array_map(fn($str) => [$str], $this->arrExtractedAddresses) )
->render();
$this->fxTitle("Unsubscribing from newsletter, stop all notifications...");
if( $this->isNotDryRun() ) {
$this->userRepository->handleBounceEmailAddress($this->arrExtractedAddresses);
}
$this->fxTitle("Deleting emails...");
if( $this->isNotProd() ) {
$this->fxInfo("🦘 Skipped in non-prod");
} elseif( $this->isNotDryRun() ) {
foreach($this->arrMessagesToDelete as $message) {
$message->delete();
}
$mailserver->expunge();
}
return $this->endWithSuccess();
}
protected function buildItemTitle($key, $item): string
{
$date = $item->getDate()->format("Y-m-d H:i:s");
$subject = mb_substr($item->getSubject(), 0, 50);
$from = $item->getFrom()->getName() . " <" . $item->getFrom()->getAddress() . ">";
return "🗓️ $date 💬 $subject ✉️ $from";
}
protected function iteratorSkipCondition($key, $item) : bool
{
$subject = $item->getSubject();
foreach(static::SUBJECT_TO_PROCESS as $check) {
$subject = mb_strtolower($subject);
$check = mb_strtolower($check);
if( str_contains($subject, $check) ) {
return false;
}
}
return true;
}
protected function processOneMessage($key, $message) : static
{
$arrAddresses = array_merge( $this->extractAddressesFromBody($message), $this->extractAddressesFromSubParts($message) );
$arrAddresses = $this->processAddresses($arrAddresses);
if( empty($arrAddresses) ) {
return $this;
}
$this->arrMessagesToDelete[] = $message;
foreach($arrAddresses as $address) {
if( in_array($address, $this->arrExtractedAddresses) ) {
continue;
}
$this->arrExtractedAddresses[] = $address;
}
return $this;
}
protected function extractAddressesFromBody(Message $message) : array
{
// Content of text/html part, if present
$body = $message->getCompleteBodyHtml();
if( empty($body) ) {
// Content of text/plain part, if present
$body = $message->getCompleteBodyText();
}
if( empty($body) ) {
return [];
}
$arrAddresses = [];
preg_match_all(static::EMAIL_ADDRESS_REGEX, $body, $arrAddresses);
$arrAddresses = reset($arrAddresses);
return $arrAddresses;
}
protected function extractAddressesFromSubParts(Message $message) : array
{
$arrAllAddresses = [];
$iterator = new \RecursiveIteratorIterator($message, \RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $part) {
$arrAddresses = [];
$partContent = $part->getContent();
preg_match_all(static::EMAIL_ADDRESS_REGEX, $partContent, $arrAddresses);
$arrAddresses = reset($arrAddresses);
$arrAllAddresses = array_merge($arrAllAddresses, $arrAddresses);
}
return $arrAllAddresses;
}
protected function processAddresses(array $arrAddresses) : array
{
$arrCleanAddresses = [];
foreach($arrAddresses as $address) {
$address = mb_strtolower($address);
$address = trim($address);
if(
str_contains($address, '@turbolab.it') || str_contains($address, 'postmaster@') ||
str_contains($address, 'mailer-daemon@')
) {
continue;
}
$arrCleanAddresses[] = $address;
}
return array_unique($arrCleanAddresses);
}
}