Skip to content

EspoCRM – Open Source CRM Application

mail sender ref

Yuri Kuznetsovd0c640064456
diff --git a/application/Espo/Core/Mail/Sender.php b/application/Espo/Core/Mail/Sender.php
index 93827bf874..46149953eb 100644
--- a/application/Espo/Core/Mail/Sender.php
+++ b/application/Espo/Core/Mail/Sender.php
@@ -34,9 +34,7 @@ use Espo\Core\Mail\Exceptions\NoSmtp;
use Espo\Core\Mail\Smtp\TransportFactory;
use Espo\Core\Name\Field;
use Espo\Core\ORM\Repository\Option\SaveOption;
-use Espo\ORM\Collection;
use Espo\ORM\EntityCollection;
-
use Espo\Core\Field\DateTime;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Log;
@@ -68,7 +66,7 @@ class Sender
{
private ?SmtpTransport $transport = null;
private bool $isGlobal = false;
- /** @var array<string, mixed> */
+ /** @var array<string, mixed> */
private array $params = [];
/** @var array<string, mixed> */
private array $overrideParams = [];
@@ -77,6 +75,14 @@ class Sender
/** @var ?iterable<Attachment> */
private $attachmentList = null;
+ private const ATTACHMENT_ATTR_CONTENTS = 'contents';
+
+ private const MESSAGE_TYPE_MULTIPART_RELATED = 'multipart/related';
+ private const MESSAGE_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
+ private const MESSAGE_TYPE_MULTIPART_MIXED = 'multipart/mixed';
+ private const MESSAGE_TYPE_TEXT_PLAIN = 'text/plain';
+ private const MESSAGE_TYPE_TEXT_HTML = 'text/html';
+
public function __construct(
private Config $config,
private EntityManager $entityManager,
@@ -86,24 +92,16 @@ class Sender
private FileStorageManager $fileStorageManager,
private ConfigDataProvider $configDataProvider,
) {
-
- /** @noinspection PhpDeprecationInspection */
$this->useGlobal();
}
- /**
- * @deprecated As of 6.0. EmailSender should be used as an access point
- * for email sending functionality. Sender instances are not meant to be reused.
- */
- public function resetParams(): self
+ private function resetParams(): void
{
$this->params = [];
$this->envelope = null;
$this->message = null;
$this->attachmentList = null;
$this->overrideParams = [];
-
- return $this;
}
/**
@@ -212,17 +210,10 @@ class Sender
return $this;
}
- /**
- * @deprecated As of v6.0. Sender class not meant to be reused. Global params is applied by default.
- * No need to reset it back.
- */
- public function useGlobal(): self
+ private function useGlobal(): void
{
$this->params = [];
-
$this->isGlobal = true;
-
- return $this;
}
/**
@@ -319,60 +310,232 @@ class Sender
}
/**
- * @deprecated As of v6.0. Use EmailSender::hasSystemSmtp.
+ * Send an email.
+ *
+ * @throws SendingError
*/
- public function hasSystemSmtp(): bool
+ public function send(Email $email): void
{
- if ($this->config->get('smtpServer')) {
- return true;
+ if ($this->isGlobal) {
+ $this->applyGlobal();
}
- if ($this->accountProvider->getSystem()) {
- return true;
+ $message = $this->message ?? new Message();
+
+ $params = array_merge($this->params, $this->overrideParams);
+
+ $this->applyFrom($email, $message, $params);
+ $this->applyReplyTo($message, $params);
+ $this->addRecipientAddresses($email, $message);
+ $this->applySubject($email, $message);
+ $this->applyBody($email, $message);
+ $this->applyMessageId($email, $message);
+
+ $message->setEncoding('UTF-8');
+
+ assert($this->transport !== null);
+
+ try {
+ $this->transport->send($message);
+ } catch (Exception $e) {
+ $this->resetParams();
+ $this->useGlobal();
+
+ $this->handleException($e);
}
- return false;
+ $email
+ ->setStatus(Email::STATUS_SENT)
+ ->setDateSent(DateTime::createNow())
+ ->setSendAt(null);
+
+ $this->resetParams();
+ $this->useGlobal();
+ }
+
+ /**
+ * @return MimePart[]
+ */
+ private function getInlineAttachmentPartList(Email $email): array
+ {
+ $list = [];
+
+ foreach ($email->getInlineAttachmentList() as $attachment) {
+ $contents = $attachment->has(self::ATTACHMENT_ATTR_CONTENTS) ?
+ $attachment->get(self::ATTACHMENT_ATTR_CONTENTS) :
+ $this->fileStorageManager->getContents($attachment);
+
+ $mimePart = new MimePart($contents);
+
+ $mimePart->disposition = Mime::DISPOSITION_INLINE;
+ $mimePart->encoding = Mime::ENCODING_BASE64;
+ $mimePart->id = $attachment->getId();
+
+ if ($attachment->getType()) {
+ $mimePart->type = $attachment->getType();
+ }
+
+ $list[] = $mimePart;
+ }
+
+ return $list;
}
/**
- * Send an email.
- *
- * @param ?array<string, mixed> $params @deprecated As of v6.0. Use withParams.
- * @param ?Message $message @deprecated As of v6.0. Use withMessage.
- * @param iterable<Attachment> $attachmentList @deprecated As of v6.0. Use withAttachments.
* @throws SendingError
*/
- public function send(
- Email $email,
- ?array $params = [],
- ?Message $message = null,
- iterable $attachmentList = []
- ): void {
+ private function handleException(Exception $e): never
+ {
+ if ($e instanceof ProtocolRuntimeException) {
+ $message = "unknownError";
- if ($this->isGlobal) {
- $this->applyGlobal();
+ if (
+ stripos($e->getMessage(), 'password') !== false ||
+ stripos($e->getMessage(), 'credentials') !== false ||
+ stripos($e->getMessage(), '5.7.8') !== false
+ ) {
+ $message = 'invalidCredentials';
+ }
+
+ $this->log->error("Email sending error: " . $e->getMessage());
+
+ throw new SendingError($message);
}
- $message = $this->message ?? $message ?? new Message();
+ throw new SendingError($e->getMessage());
+ }
- $params = $params ?? [];
+ static public function generateMessageId(Email $email): string
+ {
+ $rand = mt_rand(1000, 9999);
- $config = $this->config;
+ $messageId = $email->getParentType() && $email->getParentId() ?
+ sprintf("%s/%s/%s/%s@espo", $email->getParentType(), $email->getParentId(), time(), $rand) :
+ sprintf("%s/%s/%s@espo", md5($email->get(Field::NAME)), time(), $rand);
- $params = array_merge(
- $this->params,
- $params,
- $this->overrideParams
- );
+ if ($email->get('isSystem')) {
+ $messageId .= '-system';
+ }
- $fromName = $params['fromName'] ?? $config->get('outboundEmailFromName');
+ return $messageId;
+ }
+
+ /**
+ * @deprecated As of v6.0. Use withEnvelopeOptions.
+ *
+ * @param array<string, mixed> $options
+ */
+ public function setEnvelopeOptions(array $options): self
+ {
+ $this->envelope = new Envelope($options);
+
+ return $this;
+ }
+
+ private function addRecipientAddresses(Email $email, Message $message): void
+ {
+ $value = $email->get('to');
+
+ if ($value) {
+ foreach (explode(';', $value) as $address) {
+ $message->addTo(trim($address));
+ }
+ }
+
+ $value = $email->get('cc');
+
+ if ($value) {
+ foreach (explode(';', $value) as $address) {
+ $message->addCC(trim($address));
+ }
+ }
+
+ $value = $email->get('bcc');
+
+ if ($value) {
+ foreach (explode(';', $value) as $address) {
+ $message->addBCC(trim($address));
+ }
+ }
+
+ $value = $email->get('replyTo');
+
+ if ($value) {
+ foreach (explode(';', $value) as $address) {
+ $message->addReplyTo(trim($address));
+ }
+ }
+ }
+
+ /**
+ * @return MimePart[]
+ */
+ private function getAttachmentParts(Email $email): array
+ {
+ /** @var EntityCollection<Attachment> $collection */
+ $collection = $this->entityManager
+ ->getCollectionFactory()
+ ->create(Attachment::ENTITY_TYPE);
+
+ if (!$email->isNew()) {
+ foreach ($email->getAttachments() as $attachment) {
+ $collection[] = $attachment;
+ }
+ }
+
+ if ($this->attachmentList !== null) {
+ foreach ($this->attachmentList as $attachment) {
+ $collection[] = $attachment;
+ }
+ }
+
+ $attachmentPartList = [];
+
+ foreach ($collection as $attachment) {
+ $contents = $attachment->has(self::ATTACHMENT_ATTR_CONTENTS) ?
+ $attachment->get(self::ATTACHMENT_ATTR_CONTENTS) :
+ $this->fileStorageManager->getContents($attachment);
+
+ $mimePart = new MimePart($contents);
+
+ $mimePart->disposition = Mime::DISPOSITION_ATTACHMENT;
+ $mimePart->encoding = Mime::ENCODING_BASE64;
+ $mimePart->filename = $this->prepareAttachmentFileName($attachment);
+
+ if ($attachment->getType()) {
+ $mimePart->type = $attachment->getType();
+ }
+
+ $attachmentPartList[] = $mimePart;
+ }
+
+ return $attachmentPartList;
+ }
+
+ private function prepareAttachmentFileName(mixed $attachment): string
+ {
+ $namePart = base64_encode($attachment->getName() ?? '');
+
+ return "=?utf-8?B?$namePart?=";
+ }
+
+ /**
+ * @param array<string, mixed> $params
+ * @throws NoSmtp
+ */
+ private function applyFrom(Email $email, Message $message, array $params): void
+ {
+ $fromName = $params['fromName'] ?? $this->config->get('outboundEmailFromName');
$fromAddress = $email->get('from');
if ($fromAddress) {
$fromAddress = trim($fromAddress);
} else {
- if (empty($params['fromAddress']) && !$this->configDataProvider->getSystemOutboundAddress()) {
+ if (
+ empty($params['fromAddress']) &&
+ !$this->configDataProvider->getSystemOutboundAddress()
+ ) {
throw new NoSmtp('outboundEmailFromAddress is not specified in config.');
}
@@ -396,75 +559,64 @@ class Sender
$senderHeader->setAddress($fromAddress);
$message->getHeaders()->addHeader($senderHeader);
+ }
- if (!empty($params['replyToAddress'])) {
- $message->setReplyTo(
- $params['replyToAddress'],
- $params['replyToName'] ?? null
- );
+ /**
+ * @param array<string, mixed> $params
+ */
+ private function applyReplyTo(Message $message, array $params): void
+ {
+ $address = $params['replyToAddress'] ?? null;
+ $name = $params['replyToName'] ?? null;
+
+ if (!$address) {
+ return;
}
- $this->addAddresses($email, $message);
+ $message->setReplyTo($address, $name);
+ }
- $attachmentPartList = [];
+ private function applyMessageId(Email $email, Message $message): void
+ {
+ $messageId = $email->getMessageId();
- /** @var EntityCollection<Attachment> $attachmentCollection */
- $attachmentCollection = $this->entityManager
- ->getCollectionFactory()
- ->create(Attachment::ENTITY_TYPE);
+ if (
+ !$messageId ||
+ strlen($messageId) < 4 ||
+ str_starts_with($messageId, 'dummy:')
+ ) {
+ $messageId = $this->generateMessageId($email);
- if (!$email->isNew()) {
- /** @var Collection<Attachment> $relatedAttachmentCollection */
- $relatedAttachmentCollection = $this->entityManager
- ->getRelation($email, 'attachments')
- ->find();
+ $email->setMessageId('<' . $messageId . '>');
- foreach ($relatedAttachmentCollection as $attachment) {
- $attachmentCollection[] = $attachment;
+ if ($email->hasId()) {
+ $this->entityManager->saveEntity($email, [SaveOption::SILENT => true]);
}
+ } else {
+ $messageId = substr($messageId, 1, strlen($messageId) - 2);
}
- if ($this->attachmentList !== null) {
- $attachmentList = $this->attachmentList;
- }
-
- foreach ($attachmentList as $attachment) {
- $attachmentCollection[] = $attachment;
- }
-
- foreach ($attachmentCollection as $a) {
- $contents = $a->has('contents') ?
- $a->get('contents') :
- $this->fileStorageManager->getContents($a);
-
- $attachment = new MimePart($contents);
-
- $attachment->disposition = Mime::DISPOSITION_ATTACHMENT;
- $attachment->encoding = Mime::ENCODING_BASE64;
- $attachment->filename ='=?utf-8?B?' . base64_encode($a->getName() ?? '') . '?=';
-
- if ($a->getType()) {
- $attachment->type = $a->getType();
- }
+ $header = (new MessageIdHeader())->setId($messageId);
- $attachmentPartList[] = $attachment;
- }
+ $message->getHeaders()->addHeader($header);
+ }
+ private function applyBody(Email $email, Message $message): void
+ {
+ $attachmentPartList = $this->getAttachmentParts($email);
$inlineAttachmentPartList = $this->getInlineAttachmentPartList($email);
- $message->setSubject($email->getSubject() ?? '');
-
$body = new MimeMessage();
$textPart = (new MimePart($email->getBodyPlainForSending()))
- ->setType('text/plain')
+ ->setType(self::MESSAGE_TYPE_TEXT_PLAIN)
->setEncoding(Mime::ENCODING_QUOTEDPRINTABLE)
->setCharset('utf-8');
$htmlPart = $email->isHtml() ?
(new MimePart($email->getBodyForSending()))
->setEncoding(Mime::ENCODING_QUOTEDPRINTABLE)
- ->setType('text/html')
+ ->setType(self::MESSAGE_TYPE_TEXT_HTML)
->setCharset('utf-8') :
null;
@@ -475,14 +627,14 @@ class Sender
if ($hasAttachments || $hasInlineAttachments) {
if ($htmlPart) {
- $messageType = 'multipart/mixed';
+ $messageType = self::MESSAGE_TYPE_MULTIPART_MIXED;
$alternative = (new MimeMessage())
->addPart($textPart)
->addPart($htmlPart);
$alternativePart = (new MimePart($alternative->generateMessage()))
- ->setType('multipart/alternative')
+ ->setType(self::MESSAGE_TYPE_MULTIPART_ALTERNATIVE)
->setBoundary($alternative->getMime()->boundary());
if ($hasInlineAttachments && $hasAttachments) {
@@ -494,13 +646,13 @@ class Sender
$body->addPart(
(new MimePart($related->generateMessage()))
- ->setType('multipart/related')
+ ->setType(self::MESSAGE_TYPE_MULTIPART_RELATED)
->setBoundary($related->getMime()->boundary())
);
}
if ($hasInlineAttachments && !$hasAttachments) {
- $messageType = 'multipart/related';
+ $messageType = self::MESSAGE_TYPE_MULTIPART_RELATED;
$body->addPart($alternativePart);
@@ -515,7 +667,7 @@ class Sender
}
if (!$htmlPart) {
- $messageType = 'multipart/related';
+ $messageType = self::MESSAGE_TYPE_MULTIPART_RELATED;
$body->addPart($textPart);
@@ -531,192 +683,41 @@ class Sender
if ($email->isHtml()) {
$body->setParts([$textPart, $htmlPart]);
- $messageType = 'multipart/alternative';
+ $messageType = self::MESSAGE_TYPE_MULTIPART_ALTERNATIVE;
} else {
$body = $email->getBodyPlainForSending();
- $messageType = 'text/plain';
+ $messageType = self::MESSAGE_TYPE_TEXT_PLAIN;
}
}
$message->setBody($body);
- if ($messageType === 'text/plain') {
+ if ($messageType === self::MESSAGE_TYPE_TEXT_PLAIN) {
if ($message->getHeaders()->has('content-type')) {
$message->getHeaders()->removeHeader('content-type');
}
$message->getHeaders()->addHeaderLine('Content-Type', 'text/plain; charset=UTF-8');
- } else {
- if (!$message->getHeaders()->has('content-type')) {
- $contentTypeHeader = new ContentTypeHeader();
-
- $message->getHeaders()->addHeader($contentTypeHeader);
- }
- /** @phpstan-ignore-next-line */
- $message->getHeaders()->get('content-type')->setType($messageType);
+ return;
}
- $message->setEncoding('UTF-8');
+ if (!$message->getHeaders()->has('content-type')) {
+ $contentTypeHeader = new ContentTypeHeader();
- try {
- $messageId = $email->getMessageId();
-
- if (
- !$messageId ||
- strlen($messageId) < 4 ||
- str_starts_with($messageId, 'dummy:')
- ) {
- $messageId = $this->generateMessageId($email);
-
- $email->setMessageId('<' . $messageId . '>');
-
- if ($email->hasId()) {
- $this->entityManager->saveEntity($email, [SaveOption::SILENT => true]);
- }
- } else {
- $messageId = substr($messageId, 1, strlen($messageId) - 2);
- }
-
- $message->getHeaders()->addHeader(
- (new MessageIdHeader())->setId($messageId)
- );
-
- assert($this->transport !== null);
-
- $this->transport->send($message);
-
- $email
- ->setStatus(Email::STATUS_SENT)
- ->setDateSent(DateTime::createNow())
- ->setSendAt(null);
- } catch (Exception $e) {
- /** @noinspection PhpDeprecationInspection */
- $this->resetParams();
- /** @noinspection PhpDeprecationInspection */
- $this->useGlobal();
-
- $this->handleException($e);
+ $message->getHeaders()->addHeader($contentTypeHeader);
}
- /** @noinspection PhpDeprecationInspection */
- $this->resetParams();
- /** @noinspection PhpDeprecationInspection */
- $this->useGlobal();
- }
-
- /**
- * @return MimePart[]
- */
- private function getInlineAttachmentPartList(Email $email): array
- {
- $list = [];
-
- foreach ($email->getInlineAttachmentList() as $a) {
- $contents = $a->has('contents') ?
- $a->get('contents') :
- $this->fileStorageManager->getContents($a);
-
- $attachment = new MimePart($contents);
-
- $attachment->disposition = Mime::DISPOSITION_INLINE;
- $attachment->encoding = Mime::ENCODING_BASE64;
- $attachment->id = $a->getId();
-
- if ($a->getType()) {
- $attachment->type = $a->getType();
- }
+ $contentTypeHeader = $message->getHeaders()->get('content-type');
- $list[] = $attachment;
- }
+ assert($contentTypeHeader instanceof ContentTypeHeader);
- return $list;
+ $contentTypeHeader->setType($messageType);
}
- /**
- * @throws SendingError
- */
- private function handleException(Exception $e): never
- {
- if ($e instanceof ProtocolRuntimeException) {
- $message = "unknownError";
-
- if (
- stripos($e->getMessage(), 'password') !== false ||
- stripos($e->getMessage(), 'credentials') !== false ||
- stripos($e->getMessage(), '5.7.8') !== false
- ) {
- $message = 'invalidCredentials';
- }
-
- $this->log->error("Email sending error: " . $e->getMessage());
-
- throw new SendingError($message);
- }
-
- throw new SendingError($e->getMessage());
- }
-
- static public function generateMessageId(Email $email): string
- {
- $rand = mt_rand(1000, 9999);
-
- $messageId = $email->getParentType() && $email->getParentId() ?
- sprintf("%s/%s/%s/%s@espo", $email->getParentType(), $email->getParentId(), time(), $rand) :
- sprintf("%s/%s/%s@espo", md5($email->get(Field::NAME)), time(), $rand);
-
- if ($email->get('isSystem')) {
- $messageId .= '-system';
- }
-
- return $messageId;
- }
-
- /**
- * @deprecated As of v6.0. Use withEnvelopeOptions.
- *
- * @param array<string, mixed> $options
- */
- public function setEnvelopeOptions(array $options): self
- {
- $this->envelope = new Envelope($options);
-
- return $this;
- }
-
- private function addAddresses(Email $email, Message $message): void
+ private function applySubject(Email $email, Message $message): void
{
- $value = $email->get('to');
-
- if ($value) {
- foreach (explode(';', $value) as $address) {
- $message->addTo(trim($address));
- }
- }
-
- $value = $email->get('cc');
-
- if ($value) {
- foreach (explode(';', $value) as $address) {
- $message->addCC(trim($address));
- }
- }
-
- $value = $email->get('bcc');
-
- if ($value) {
- foreach (explode(';', $value) as $address) {
- $message->addBCC(trim($address));
- }
- }
-
- $value = $email->get('replyTo');
-
- if ($value) {
- foreach (explode(';', $value) as $address) {
- $message->addReplyTo(trim($address));
- }
- }
+ $message->setSubject($email->getSubject() ?? '');
}
}