-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
MailHelper.php
2101 lines (1788 loc) · 61.5 KB
/
MailHelper.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Mautic\EmailBundle\Helper;
use Doctrine\ORM\ORMException;
use Mautic\AssetBundle\Entity\Asset;
use Mautic\CoreBundle\Factory\MauticFactory;
use Mautic\CoreBundle\Helper\EmojiHelper;
use Mautic\CoreBundle\Helper\InputHelper;
use Mautic\EmailBundle\EmailEvents;
use Mautic\EmailBundle\Entity\Email;
use Mautic\EmailBundle\Entity\Stat;
use Mautic\EmailBundle\Event\EmailSendEvent;
use Mautic\EmailBundle\Exception\InvalidEmailException;
use Mautic\EmailBundle\Form\Type\ConfigType;
use Mautic\EmailBundle\Mailer\Exception\BatchQueueMaxException;
use Mautic\EmailBundle\Mailer\Message\MauticMessage;
use Mautic\EmailBundle\Mailer\Transport\TokenTransportInterface;
use Mautic\LeadBundle\Entity\Lead;
use Mautic\LeadBundle\Model\LeadModel;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mailer\Transport\TransportInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Header\HeaderInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;
/**
* Class MailHelper.
*/
class MailHelper
{
public const QUEUE_RESET_TO = 'RESET_TO';
public const QUEUE_FULL_RESET = 'FULL_RESET';
public const QUEUE_DO_NOTHING = 'DO_NOTHING';
public const QUEUE_NOTHING_IF_FAILED = 'IF_FAILED';
public const QUEUE_RETURN_ERRORS = 'RETURN_ERRORS';
public const EMAIL_TYPE_TRANSACTIONAL = 'transactional';
public const EMAIL_TYPE_MARKETING = 'marketing';
/**
* @var MauticFactory
*/
protected $factory;
protected MailerInterface $mailer;
protected $transport;
/**
* @var Environment
*/
protected $twig;
/**
* @var null
*/
protected $dispatcher;
/**
* @var MauticMessage
*/
public $message;
/**
* @var string|array<string, string>
*/
protected $from;
protected $systemFrom;
/**
* @var string
*/
protected $replyTo;
/**
* @var string
*/
protected $systemReplyTo;
/**
* @var string
*/
protected $returnPath;
/**
* @var array
*/
protected $errors = [];
/**
* @var array|Lead
*/
protected $lead;
/**
* @var bool
*/
protected $internalSend = false;
/**
* @var null
*/
protected $idHash;
/**
* @var bool
*/
protected $idHashState = true;
/**
* @var bool
*/
protected $appendTrackingPixel = false;
/**
* @var array
*/
protected $source = [];
/**
* @var Email|null
*/
protected $email;
protected ?string $emailType = null;
/**
* @var array
*/
protected $globalTokens = [];
/**
* @var array
*/
protected $eventTokens = [];
/**
* Tells the helper that the transport supports tokenized emails (likely HTTP API).
*
* @var bool
*/
protected $tokenizationEnabled = false;
/**
* Use queue mode when sending email through this mailer; this requires a transport that supports tokenization and the use of queue/flushQueue.
*
* @var bool
*/
protected $queueEnabled = false;
/**
* @var array
*/
protected $queuedRecipients = [];
/**
* @var array
*/
public $metadata = [];
/**
* @var string
*/
protected $subject = '';
/**
* @var string
*/
protected $plainText = '';
/**
* @var bool
*/
protected $plainTextSet = false;
/**
* @var array
*/
protected $assets = [];
/**
* @var array
*/
protected $attachedAssets = [];
/**
* @var array
*/
protected $assetStats = [];
/**
* @var array
*/
protected $headers = [];
/**
* @var array
*/
protected $body = [
'content' => '',
'contentType' => 'text/html',
'charset' => null,
];
/**
* Cache for lead owners.
*
* @var array
*/
protected static $leadOwners = [];
/**
* @var bool
*/
protected $fatal = false;
/**
* Simply a md5 of the content so that event listeners can easily determine if the content has been changed.
*
* @var string
*/
private $contentHash;
/**
* @var array
*/
private $copies = [];
/**
* @var array
*/
private $embedImagesReplaces = [];
public function __construct(MauticFactory $factory, MailerInterface $mailer, $from = null)
{
$this->factory = $factory;
$this->mailer = $mailer;
$this->transport = $this->getTransport();
$systemFromEmail = $factory->getParameter('mailer_from_email');
$systemReplyToEmail = $factory->getParameter('mailer_reply_to_email');
$systemFromName = $this->cleanName(
$factory->getParameter('mailer_from_name')
);
$this->setDefaultFrom($from, [$systemFromEmail => $systemFromName]);
$this->setDefaultReplyTo($systemReplyToEmail, $this->from);
$this->returnPath = $factory->getParameter('mailer_return_path');
// Check if batching is supported by the transport
if ($this->transport instanceof TokenTransportInterface) {
$this->tokenizationEnabled = true;
}
$this->message = $this->getMessageInstance();
}
/**
* Mirrors previous MauticFactory functionality.
*
* @param bool $cleanSlate
*
* @return $this
*/
public function getMailer($cleanSlate = true)
{
$this->reset($cleanSlate);
return $this;
}
/**
* Mirrors previous MauticFactory functionality.
*
* @param bool $cleanSlate
*
* @return $this
*/
public function getSampleMailer($cleanSlate = true)
{
return $this->getMailer($cleanSlate);
}
/**
* Send the message.
*
* @param bool $dispatchSendEvent
* @param bool $isQueueFlush (a tokenized/batch send via API such as Mandrill)
*
* @return bool
*/
public function send($dispatchSendEvent = false, $isQueueFlush = false)
{
if ($this->tokenizationEnabled && !empty($this->queuedRecipients) && !$isQueueFlush) {
// This transport uses tokenization and queue()/flushQueue() was not used therefore use them in order
// properly populate metadata for this transport
if ($result = $this->queue($dispatchSendEvent)) {
$result = $this->flushQueue(['To', 'Cc', 'Bcc']);
}
return $result;
}
// Set from email
$ownerSignature = false;
if (!$isQueueFlush) {
$emailToSend = $this->getEmail();
if (!empty($emailToSend)) {
if ($emailToSend->getUseOwnerAsMailer()) {
$owner = $this->getContactOwner($this->lead);
if (!empty($owner)) {
$this->setFrom($owner['email'], $owner['first_name'].' '.$owner['last_name']);
$ownerSignature = $this->getContactOwnerSignature($owner);
if (null !== $emailToSend->getReplyToAddress()) {
$this->setReplyTo($emailToSend->getReplyToAddress());
} else {
$this->setReplyTo($owner['email']);
}
} else {
$this->setFrom($this->systemFrom, null);
$this->setReplyTo($this->replyTo);
}
} elseif (!empty($emailToSend->getFromAddress())) {
$this->setFrom($emailToSend->getFromAddress(), $emailToSend->getFromName());
} else {
$this->setFrom($this->from, null);
}
} else {
$this->setFrom($this->from, null);
}
} // from is set in flushQueue
if (empty($this->message->getReplyTo()) && !empty($this->replyTo)) {
$this->setReplyTo($this->replyTo);
}
// Set system return path if applicable
if (!$isQueueFlush && ($bounceEmail = $this->generateBounceEmail())) {
$this->message->returnPath($bounceEmail);
} elseif (!empty($this->returnPath)) {
$this->message->returnPath($this->returnPath);
}
if (empty($this->fatal)) {
if (!$isQueueFlush) {
// Search/replace tokens if this is not a queue flush
// Generate tokens from listeners
if ($dispatchSendEvent) {
$this->dispatchSendEvent();
}
// Queue an asset stat if applicable
$this->queueAssetDownloadEntry();
}
$this->message->subject($this->subject);
// Only set body if not empty or if plain text is empty - this ensures an empty HTML body does not show for
// messages only with plain text
if (!empty($this->body['content']) || empty($this->plainText)) {
$this->message->html($this->body['content'], $this->body['charset'] ?? 'utf-8');
}
$this->setMessagePlainText();
$this->setMessageHeaders();
if (!$isQueueFlush) {
// Replace token content
$tokens = $this->getTokens();
if ($ownerSignature) {
$tokens['{signature}'] = $ownerSignature;
}
// Set metadata if applicable
foreach ($this->queuedRecipients as $email => $name) {
$this->message->addMetadata($email, $this->buildMetadata($name, $tokens));
}
if (!empty($tokens)) {
// Replace tokens
$search = array_keys($tokens);
$replace = $tokens;
self::searchReplaceTokens($search, $replace, $this->message);
}
}
if (true === $this->factory->getParameter('mailer_convert_embed_images')) {
$this->convertEmbedImages();
}
// Attach assets
if (!empty($this->assets)) {
/** @var \Mautic\AssetBundle\Entity\Asset $asset */
foreach ($this->assets as $asset) {
if (!in_array($asset->getId(), $this->attachedAssets)) {
$this->attachedAssets[] = $asset->getId();
$this->attachFile(
$asset->getFilePath(),
$asset->getOriginalFileName(),
$asset->getMime()
);
}
}
}
try {
$this->mailer->send($this->message);
} catch (TransportExceptionInterface $exception) {
/*
The nature of symfony/mailer is working with transactional emails only
if a message fails to send, all the contacts on that message will be considered failed
*/
$failures = $this->tokenizationEnabled ? array_keys($this->message->getMetadata()) : [];
// Exception encountered when sending so all recipients are considered failures
$this->errors['failures'] = array_unique(
array_merge(
$failures,
array_keys((array) $this->message->getTo()),
array_keys((array) $this->message->getCc()),
array_keys((array) $this->message->getBcc())
)
);
$this->logError($exception->getMessage());
}
}
$error = empty($this->errors);
if (!$isQueueFlush) {
$this->createAssetDownloadEntries();
} // else handled in flushQueue
return $error;
}
/**
* If batching is supported and enabled, the message will be queued and will on be sent upon flushQueue().
* Otherwise, the message will be sent to the transport immediately.
*
* @param bool $dispatchSendEvent
* @param string $returnMode What should happen post send/queue to $this->message after the email send is attempted.
* Options are:
* RESET_TO resets the to recipients and resets errors
* FULL_RESET creates a new MauticMessage instance and resets errors
* DO_NOTHING leaves the current errors array and MauticMessage instance intact
* NOTHING_IF_FAILED leaves the current errors array MauticMessage instance intact if it fails, otherwise reset_to
* RETURN_ERROR return an array of [success, $errors]; only one applicable if message is queued
*
* @return bool|array
*/
public function queue($dispatchSendEvent = false, $returnMode = self::QUEUE_RESET_TO)
{
if ($this->tokenizationEnabled) {
// Dispatch event to get custom tokens from listeners
if ($dispatchSendEvent) {
$this->dispatchSendEvent();
}
// Metadata has to be set for each recipient
foreach ($this->queuedRecipients as $email => $name) {
$fromKey = 'default';
$tokens = $this->getTokens();
if ($owner = $this->getContactOwner($this->lead)) {
$fromKey = $owner['email'];
// Override default signature with owner
if ($ownerSignature = $this->getContactOwnerSignature($owner)) {
$tokens['{signature}'] = $ownerSignature;
}
}
if (!isset($this->metadata[$fromKey])) {
$this->metadata[$fromKey] = [
'from' => $owner,
'contacts' => [],
];
}
$this->metadata[$fromKey]['contacts'][$email] = $this->buildMetadata($name, $tokens);
}
// Reset recipients
$this->queuedRecipients = [];
// Assume success
return (self::QUEUE_RETURN_ERRORS) ? [true, []] : true;
} else {
$success = $this->send($dispatchSendEvent);
// Reset the message for the next
$this->queuedRecipients = [];
// Reset message
switch (strtoupper($returnMode)) {
case self::QUEUE_RESET_TO:
$this->message->to();
$this->clearErrors();
break;
case self::QUEUE_NOTHING_IF_FAILED:
if ($success) {
$this->message->to();
$this->clearErrors();
}
break;
case self::QUEUE_FULL_RESET:
$this->message = $this->getMessageInstance();
$this->attachedAssets = [];
$this->clearErrors();
break;
case self::QUEUE_RETURN_ERRORS:
$this->message->to();
$errors = $this->getErrors();
$this->clearErrors();
return [$success, $errors];
case self::QUEUE_DO_NOTHING:
default:
// Nada
break;
}
return $success;
}
}
/**
* Send batched mail to mailer.
*
* @param array $resetEmailTypes Array of email types to clear after flusing the queue
*
* @return bool
*/
public function flushQueue($resetEmailTypes = ['To', 'Cc', 'Bcc'])
{
// Assume true unless there was a fatal error configuring the mailer because if tokenizationEnabled is false, the send happened in queue()
$flushed = empty($this->fatal);
if ($this->tokenizationEnabled && count($this->metadata) && $flushed) {
$errors = $this->errors;
$errors['failures'] = [];
$flushed = false;
foreach ($this->metadata as $fromKey => $metadatum) {
// Whatever is in the message "to" should be ignored as we will send to the contacts grouped by from addresses
// This prevents mailers such as sparkpost from sending duplicates to contacts
$this->message->to();
$this->errors = [];
$email = $this->getEmail();
if (!empty($email)) {
if ($email->getUseOwnerAsMailer() && 'default' !== $fromKey) {
$this->setFrom($metadatum['from']['email'], $metadatum['from']['first_name'].' '.$metadatum['from']['last_name']);
} elseif (!empty($email->getFromAddress())) {
$this->setFrom($email->getFromAddress(), $email->getFromName());
} else {
$this->setFrom($this->systemFrom, null);
}
} else {
$this->setFrom($this->from, null);
}
foreach ($metadatum['contacts'] as $email => $contact) {
$this->message->addMetadata($email, $contact);
// Add asset stats if applicable
if (!empty($contact['leadId'])) {
$this->queueAssetDownloadEntry($email, $contact);
}
$this->message->to(new Address($email, $contact['name'] ?? ''));
}
$flushed = $this->send(false, true);
// Merge errors
if (isset($this->errors['failures'])) {
$errors['failures'] = array_merge($errors['failures'], $this->errors['failures']);
unset($this->errors['failures']);
}
if (!empty($this->errors)) {
$errors = array_merge($errors, $this->errors);
}
// Clear metadata for the previous recipients
$this->message->clearMetadata();
}
$this->errors = $errors;
// Clear queued to recipients
$this->queuedRecipients = [];
$this->metadata = [];
}
foreach ($resetEmailTypes as $type) {
$this->message->{$type}();
}
return $flushed;
}
/**
* Resets the mailer.
*
* @param bool $cleanSlate
*/
public function reset($cleanSlate = true)
{
$this->eventTokens = [];
$this->queuedRecipients = [];
$this->errors = [];
$this->lead = null;
$this->idHash = null;
$this->contentHash = null;
$this->internalSend = false;
$this->fatal = false;
$this->idHashState = true;
if ($cleanSlate) {
$this->appendTrackingPixel = false;
$this->queueEnabled = false;
$this->from = $this->systemFrom;
$this->replyTo = $this->systemReplyTo;
$this->headers = [];
$this->source = [];
$this->assets = [];
$this->globalTokens = [];
$this->attachedAssets = [];
$this->email = null;
$this->copies = [];
$this->message = $this->getMessageInstance();
$this->subject = '';
$this->plainText = '';
$this->plainTextSet = false;
$this->body = [
'content' => '',
'contentType' => 'text/html',
'charset' => null,
];
}
}
/**
* Search and replace tokens
* Adapted from \Swift_Plugins_DecoratorPlugin.
*
* @param array $search
* @param array $replace
*/
public static function searchReplaceTokens($search, $replace, MauticMessage &$message)
{
// Body
$body = $message->getHtmlBody();
$bodyReplaced = str_ireplace($search, $replace, $body, $updated);
if ($updated) {
$message->html($bodyReplaced);
}
unset($body, $bodyReplaced);
// Subject
$subject = $message->getSubject();
$bodyReplaced = str_ireplace($search, $replace, $subject, $updated);
if ($updated) {
$message->subject($bodyReplaced);
}
unset($subject, $bodyReplaced);
// Headers
/** @var HeaderInterface $header */
foreach ($message->getHeaders()->all() as $header) {
$headerBody = $header->getBody();
if ($headerBody instanceof \DateTimeInterface) {
// It's not possible to replace tokens in \DateTime objects
// because they can't contain tokens
continue;
}
$updated = false;
if (is_array($headerBody)) {
$bodyReplaced = [];
foreach ($headerBody as $key => $value) {
$count1 = $count2 = 0;
$key = is_string($key) ? str_ireplace($search, $replace, $key, $count1) : $key;
$value = is_string($value) ? str_ireplace($search, $replace, $value, $count2) : $value;
$bodyReplaced[$key] = $value;
if ($count1 + $count2) {
$updated = true;
}
}
} else {
$bodyReplaced = str_ireplace($search, $replace, $headerBody, $updated);
}
if (!empty($updated)) {
$header->setBody($bodyReplaced);
}
unset($headerBody, $bodyReplaced);
}
// Parts (plaintext)
$textBody = $message->getTextBody() ?? '';
$bodyReplaced = str_ireplace($search, $replace, $textBody);
if ($textBody != $bodyReplaced) {
$textBody = strip_tags($bodyReplaced);
$message->text($textBody);
}
}
/**
* @return string
*/
public static function getBlankPixel()
{
return 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
}
/**
* Add an attachment to email.
*
* @param string $filePath
* @param string $fileName
* @param string $contentType
* @param bool $inline
*/
public function attachFile($filePath, $fileName = null, $contentType = null, $inline = false)
{
if (true === $inline) {
$this->message->embedFromPath($filePath, $fileName, $contentType);
return;
}
$this->message->attachFromPath($filePath, $fileName, $contentType);
}
/**
* @param int|Asset $asset
*/
public function attachAsset($asset)
{
$model = $this->factory->getModel('asset');
if (!$asset instanceof Asset) {
$asset = $model->getEntity($asset);
if (null == $asset) {
return;
}
}
if ($asset->isPublished()) {
$asset->setUploadDir($this->factory->getParameter('upload_dir'));
$this->assets[$asset->getId()] = $asset;
}
}
/**
* Use a template as the body.
*
* @param string $template
* @param array $vars
* @param bool $returnContent
* @param null $charset
*
* @return void|string
*/
public function setTemplate($template, $vars = [], $returnContent = false, $charset = null)
{
if (null == $this->twig) {
$this->twig = $this->factory->getTwig();
}
$content = $this->twig->render($template, $vars);
unset($vars);
if ($returnContent) {
return $content;
}
$this->setBody($content, 'text/html', $charset);
unset($content);
}
/**
* Set subject.
*/
public function setSubject($subject)
{
$this->subject = $subject;
}
/**
* @return string
*/
public function getSubject()
{
return $this->subject;
}
/**
* Set a plain text part.
*/
public function setPlainText($content)
{
$this->plainText = $content;
// Update the identifier for the content
$this->contentHash = md5($this->body['content'].$this->plainText);
}
/**
* @return string
*/
public function getPlainText()
{
return $this->plainText;
}
/**
* Set plain text for $this->message, replacing if necessary.
*/
protected function setMessagePlainText()
{
if ($this->tokenizationEnabled && $this->plainTextSet) {
// No need to find and replace since tokenization happens at the transport level
return;
}
$this->message->text($this->plainText);
$this->plainTextSet = true;
}
/**
* @param string $contentType
* @param null $charset
* @param bool $ignoreTrackingPixel
*/
public function setBody($content, $contentType = 'text/html', $charset = null, $ignoreTrackingPixel = false)
{
if (!$ignoreTrackingPixel && $this->factory->getParameter('mailer_append_tracking_pixel')) {
// Append tracking pixel
$trackingImg = '<img height="1" width="1" src="{tracking_pixel}" alt="" />';
if (false !== strpos($content, '</body>')) {
$content = str_replace('</body>', $trackingImg.'</body>', $content);
} else {
$content .= $trackingImg;
}
}
// Update the identifier for the content
$this->contentHash = md5($content.$this->plainText);
$this->body = [
'content' => $content,
'contentType' => $contentType,
'charset' => $charset,
];
}
private function convertEmbedImages(): void
{
$content = $this->message->getHtmlBody();
$matches = [];
$content = strtr($content, $this->embedImagesReplaces);
$tokens = $this->getTokens();
if (preg_match_all('/<img.+?src=[\"\'](.+?)[\"\'].*?>/i', $content, $matches) > 0) {
foreach ($matches[1] as $match) {
// skip items that already embedded, or have token {tracking_pixel}
if (false !== strpos($match, 'cid:') || false !== strpos($match, '{tracking_pixel}') || array_key_exists($match, $this->embedImagesReplaces)) {
continue;
}
// skip images with tracking pixel that are already replaced.
if (isset($tokens['{tracking_pixel}']) && $match === $tokens['{tracking_pixel}']) {
continue;
}
$this->embedImagesReplaces[$match] = $this->message->embedFromPath($match);
}
$content = strtr($content, $this->embedImagesReplaces);
}
$this->message->html($content);
}
/**
* Get a copy of the raw body.
*
* @return mixed
*/
public function getBody()
{
return $this->body['content'];
}
/**
* Return the content identifier.
*
* @return string
*/
public function getContentHash()
{
return $this->contentHash;
}
/**
* Set to address(es).
*
* @return bool
*/
public function setTo($addresses, $name = null)
{
$name = $this->cleanName($name);
if (!is_array($addresses)) {
$addresses = [$addresses => $name];
} elseif (0 === array_keys($addresses)[0]) {
// We need an array of $email => $name pairs
$addresses = array_reduce($addresses, function ($address, $item) use ($name) {
$address[$item] = $name;
return $address;
}, []);
}
$this->checkBatchMaxRecipients(count($addresses));
// Convert to array of Address objects
$toAddresses = array_map(fn (string $address, ?string $name): Address => new Address($address, $name ?? ''), array_keys($addresses), $addresses);
try {
$this->message->to(...$toAddresses);
$this->queuedRecipients = array_merge($this->queuedRecipients, $addresses);
return true;
} catch (\Exception $e) {
$this->logError($e, 'to');
return false;
}
}
/**
* Add to address.
*
* @param string $address
* @param string|null $name
*
* @return bool
*/
public function addTo($address, $name = null)
{
$this->checkBatchMaxRecipients();
try {
$name = $this->cleanName($name);
$this->message->addTo(new Address($address, $name ?? ''));
$this->queuedRecipients[$address] = $name;
return true;
} catch (\Exception $e) {
$this->logError($e, 'to');
return false;
}
}
/**
* Set CC address(es).
*
* @param mixed $addresses
* @param string $name
*
* //TODO: there is a bug here, the name is not passed in CC nor in the array of addresses, we do not handle names for CC
*
* @return bool
*/
public function setCc($addresses, $name = null)
{
$this->checkBatchMaxRecipients(count($addresses), 'cc');
try {
$name = $this->cleanName($name);
$ccAddresses = [];
// The email addresses are stored in the array keys not the values
// The name of the CC is passed in the function and not in the array
foreach ($addresses as $address => $noName) {
$ccAddresses[] = new Address($address, $name ?? '');
}
$this->message->cc(...$ccAddresses);