Initial commit

This commit is contained in:
root
2026-01-19 17:44:46 +01:00
commit 823af8b11d
8721 changed files with 1130846 additions and 0 deletions

View File

@@ -0,0 +1,399 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
use Espo\Core\Acl;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Name\Field;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Select\SelectBuilderFactory;
use Espo\Core\Select\Text\MetadataProvider as TextMetadataProvider;
use Espo\Core\Templates\Entities\Company;
use Espo\Core\Templates\Entities\Person;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Entities\EmailAddress;
use Espo\Entities\InboundEmail;
use Espo\Entities\User;
use Espo\Modules\Crm\Entities\Account;
use Espo\Modules\Crm\Entities\Contact;
use Espo\Modules\Crm\Entities\Lead;
use Espo\ORM\EntityManager;
use Espo\ORM\Query\SelectBuilder;
use Espo\Repositories\EmailAddress as EmailAddressRepository;
use RuntimeException;
class AddressService
{
private const ERASED_PREFIX = 'ERASED:';
private const ATTR_EMAIL_ADDRESS = 'emailAddress';
public function __construct(
private Config $config,
private Acl $acl,
private Metadata $metadata,
private SelectBuilderFactory $selectBuilderFactory,
private EntityManager $entityManager,
private User $user,
private TextMetadataProvider $textMetadataProvider
) {}
/**
* @return array<int, array<string, mixed>>
* @throws NotFound
* @throws Forbidden
*/
public function searchInEntityType(string $entityType, string $query, int $limit): array
{
if (!in_array($entityType, $this->getHavingEmailAddressEntityTypeList())) {
throw new NotFound("No 'email' field.");
}
if (!$this->acl->checkScope($entityType, Acl\Table::ACTION_READ)) {
throw new Forbidden("No access to $entityType.");
}
if (!$this->acl->checkField($entityType, 'email')) {
throw new Forbidden("No access to field 'email' in $entityType.");
}
$result = [];
$this->findInAddressBookByEntityType($query, $limit, $entityType, $result);
return $result;
}
/**
* @return array<int, array<string, mixed>>
*/
public function searchInAddressBook(string $query, int $limit, bool $onlyActual = false): array
{
$result = [];
$entityTypeList = $this->config->get('emailAddressLookupEntityTypeList') ?? [];
$allEntityTypeList = $this->getHavingEmailAddressEntityTypeList();
foreach ($entityTypeList as $entityType) {
if (!in_array($entityType, $allEntityTypeList)) {
continue;
}
if (!$this->acl->checkScope($entityType)) {
continue;
}
$this->findInAddressBookByEntityType($query, $limit, $entityType, $result, $onlyActual);
}
$this->findInInboundEmail($query, $result);
$finalResult = [];
foreach ($result as $item) {
foreach ($finalResult as $item1) {
if ($item['emailAddress'] == $item1['emailAddress']) {
continue 2;
}
}
$finalResult[] = $item;
}
usort($finalResult, function ($item1, $item2) use ($query) {
if (!str_contains($query, '@')) {
return 0;
}
$p1 = strpos($item1['emailAddress'], $query);
$p2 = strpos($item2['emailAddress'], $query);
if ($p1 === 0 && $p2 !== 0) {
return -1;
}
if ($p1 !== 0 && $p2 !== 0) {
return 0;
}
if ($p1 !== 0 && $p2 === 0) {
return 1;
}
return 0;
});
return $finalResult;
}
/**
* @return string[]
*/
private function getHavingEmailAddressEntityTypeList(): array
{
$list = [
Account::ENTITY_TYPE,
Contact::ENTITY_TYPE,
Lead::ENTITY_TYPE,
User::ENTITY_TYPE,
];
$scopeDefs = $this->metadata->get(['scopes']);
foreach ($scopeDefs as $scope => $defs) {
if (
empty($defs['disabled']) &&
!empty($defs['type']) &&
(
$defs['type'] === Person::TEMPLATE_TYPE ||
$defs['type'] === Company::TEMPLATE_TYPE
)
) {
$list[] = $scope;
}
}
return $list;
}
/**
* @param array<int, array<string, mixed>> $result
*/
private function findInAddressBookByEntityType(
string $filter,
int $limit,
string $entityType,
array &$result,
bool $onlyActual = false
): void {
$textFilter = null;
$whereClause = [];
$byEmailAddress = false;
if (str_contains($filter, '@')) {
$byEmailAddress = true;
}
if (
!$byEmailAddress &&
mb_strlen($filter) < (int) $this->config->get('fullTextSearchMinLength') &&
$this->hasFullTextSearch($entityType)
) {
$byEmailAddress = true;
}
if ($byEmailAddress) {
$whereClause = [
'emailAddress*' => $filter . '%',
];
} else {
$textFilter = $filter;
}
$selectBuilder = $this->selectBuilderFactory
->create()
->from($entityType)
->withAccessControlFilter();
if ($textFilter) {
$selectBuilder->withTextFilter($textFilter);
}
try {
$builder = $selectBuilder
->buildQueryBuilder()
->where($whereClause)
->order('name')
->limit(0, $limit);
} catch (BadRequest|Forbidden $e) {
throw new RuntimeException($e->getMessage());
}
if ($entityType === User::ENTITY_TYPE) {
$this->handleQueryBuilderUser($builder);
}
$select = [
Field::ID,
'emailAddress',
Field::NAME,
];
if (
$this->metadata->get(['entityDefs', $entityType, 'fields', Field::NAME, 'type']) === FieldType::PERSON_NAME
) {
$select[] = 'firstName';
$select[] = 'lastName';
}
$builder->select($select);
$collection = $this->entityManager
->getRDBRepository($entityType)
->clone($builder->build())
->find();
foreach ($collection as $entity) {
$emailAddress = $entity->get(self::ATTR_EMAIL_ADDRESS);
$emailAddressData = $this->getEmailAddressRepository()->getEmailAddressData($entity);
$skipPrimaryEmailAddress = false;
if (!$emailAddress) {
continue;
}
if (str_starts_with($emailAddress, self::ERASED_PREFIX)) {
$skipPrimaryEmailAddress = true;
}
if ($onlyActual) {
if ($entity->get('emailAddressIsOptedOut')) {
$skipPrimaryEmailAddress = true;
}
foreach ($emailAddressData as $item) {
if ($emailAddress !== $item->emailAddress) {
continue;
}
if (!empty($item->invalid)) {
$skipPrimaryEmailAddress = true;
}
}
}
if (!$skipPrimaryEmailAddress) {
$result[] = [
'emailAddress' => $emailAddress,
'entityName' => $entity->get(Field::NAME),
'entityType' => $entityType,
'entityId' => $entity->getId(),
];
}
foreach ($emailAddressData as $item) {
if ($emailAddress === $item->emailAddress) {
continue;
}
if (str_starts_with($item->emailAddress, self::ERASED_PREFIX)) {
continue;
}
if ($onlyActual) {
if (!empty($item->invalid)) {
continue;
}
if (!empty($item->optOut)) {
continue;
}
}
$result[] = [
'emailAddress' => $item->emailAddress,
'entityName' => $entity->get(Field::NAME),
'entityType' => $entityType,
'entityId' => $entity->getId(),
];
}
}
}
/**
* @param array<int, array<string, mixed>> $result
*/
private function findInInboundEmail(string $query, array &$result): void
{
if ($this->user->isPortal()) {
return;
}
$list = $this->entityManager
->getRDBRepository(InboundEmail::ENTITY_TYPE)
->select([
'id',
'name',
'emailAddress',
])
->where([
'emailAddress*' => $query . '%',
])
->order('name')
->find();
foreach ($list as $item) {
$result[] = [
'emailAddress' => $item->getEmailAddress(),
'entityName' => $item->getName(),
'entityType' => InboundEmail::ENTITY_TYPE,
'entityId' => $item->getId(),
];
}
}
private function hasFullTextSearch(string $entityType): bool
{
return $this->textMetadataProvider->hasFullTextSearch($entityType);
}
private function handleQueryBuilderUser(SelectBuilder $queryBuilder): void
{
/*if ($this->acl->getPermissionLevel('portalPermission') === Table::LEVEL_NO) {
$queryBuilder->where([
'type!=' => User::TYPE_PORTAL,
]);
}*/
$queryBuilder->where([
'isActive' => true,
'type!=' => [
User::TYPE_PORTAL,
User::TYPE_API,
User::TYPE_SYSTEM,
User::TYPE_SUPER_ADMIN,
],
]);
}
private function getEmailAddressRepository(): EmailAddressRepository
{
/** @var EmailAddressRepository */
return $this->entityManager->getRepository(EmailAddress::ENTITY_TYPE);
}
}

View File

@@ -0,0 +1,65 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Email\InboxService;
/**
* Unmark emails as important.
*/
class DeleteInboxImportant implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$ids = $data->ids ?? null;
$id = $data->id ?? null;
if ($ids === null && is_string($id)) {
$ids = [$id];
}
if (!is_array($ids)) {
throw new BadRequest("No `ids`.");
}
$this->inboxService->markAsNotImportantIdList($ids);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,65 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Email\InboxService;
/**
* Retrieves emails from trash.
*/
class DeleteInboxInTrash implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$ids = $data->ids ?? null;
$id = $data->id ?? null;
if ($ids === null && is_string($id)) {
$ids = [$id];
}
if (!is_array($ids)) {
throw new BadRequest("No `ids`.");
}
$this->inboxService->retrieveFromTrashIdList($ids);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,65 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Email\InboxService;
/**
* Unmark emails as read.
*/
class DeleteInboxRead implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$ids = $data->ids ?? null;
$id = $data->id ?? null;
if ($ids === null && is_string($id)) {
$ids = [$id];
}
if (!is_array($ids)) {
throw new BadRequest("No `ids`.");
}
$this->inboxService->markAsNotReadIdList($ids);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Acl;
use Espo\Core\Acl\Table;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\Forbidden;
use Espo\Entities\Email as EmailEntity;
use Espo\Tools\EmailTemplate\InsertField\Service as InsertFieldService;
class GetInsertFieldData implements Action
{
public function __construct(
private InsertFieldService $service,
private Acl $acl
) {}
public function process(Request $request): Response
{
if (!$this->acl->checkScope(EmailEntity::ENTITY_TYPE, Table::ACTION_CREATE)) {
throw new Forbidden();
}
$data = $this->service->getData(
$request->getQueryParam('parentType'),
$request->getQueryParam('parentId'),
$request->getQueryParam('to')
);
return ResponseComposer::json($data);
}
}

View File

@@ -0,0 +1,48 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Tools\Email\InboxService;
class GetNotReadCounts implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$data = $this->inboxService->getFoldersNotReadCounts();
return ResponseComposer::json($data);
}
}

View File

@@ -0,0 +1,87 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Tools\Attachment\FieldData;
use Espo\Tools\Email\Service;
/**
* Copies email attachments.
*/
class PostAttachmentsCopy implements Action
{
public function __construct(private Service $service) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id');
if (!$id) {
throw new BadRequest();
}
$data = $request->getParsedBody();
$field = $data->field ?? null;
$parentType = $data->parentType ?? null;
$relatedType = $data->relatedType ?? null;
if (!$field) {
throw new BadRequest("No `field`.");
}
try {
$fieldData = new FieldData($field, $parentType, $relatedType);
} catch (Error $e) {
throw new BadRequest($e->getMessage());
}
$list = $this->service->copyAttachments($id, $fieldData);
$ids = array_map(fn ($item) => $item->getId(), $list);
$names = (object) [];
foreach ($list as $item) {
$names->{$item->getId()} = $item->getName();
}
return ResponseComposer::json([
'ids' => $ids,
'names' => $names,
]);
}
}

View File

@@ -0,0 +1,75 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Email\InboxService;
/**
* Moves emails to a folder.
*/
class PostFolder implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$folderId = $request->getRouteParam('folderId');
if (!$folderId) {
throw new BadRequest();
}
$data = $request->getParsedBody();
$ids = $data->ids ?? null;
$id = $data->id ?? null;
if ($ids === null && is_string($id)) {
$ids = [$id];
}
if (!is_array($ids)) {
throw new BadRequest("No `ids`.");
}
if (count($ids) === 1) {
$this->inboxService->moveToFolder($ids[0], $folderId);
}
$this->inboxService->moveToFolderIdList($ids, $folderId);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,82 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Acl;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Entities\Email;
use Espo\Entities\User;
use Espo\Tools\Email\ImportEmlService;
/**
* @noinspection PhpUnused
*/
class PostImportEml implements Action
{
public function __construct(
private Acl $acl,
private User $user,
private ImportEmlService $service,
) {}
public function process(Request $request): Response
{
$this->checkAccess();
$fileId = $request->getParsedBody()->fileId ?? null;
if (!is_string($fileId)) {
throw new BadRequest("No 'fileId'.");
}
$email = $this->service->import($fileId, $this->user->getId());
return ResponseComposer::json(['id' => $email->getId()]);
}
/**
* @throws Forbidden
*/
private function checkAccess(): void
{
if (!$this->acl->checkScope(Email::ENTITY_TYPE, Acl\Table::ACTION_CREATE)) {
throw new Forbidden("No 'create' access.");
}
if (!$this->acl->checkScope('Import')) {
throw new Forbidden("No access to 'Import'.");
}
}
}

View File

@@ -0,0 +1,65 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Email\InboxService;
/**
* Marks emails as important.
*/
class PostInboxImportant implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$ids = $data->ids ?? null;
$id = $data->id ?? null;
if ($ids === null && is_string($id)) {
$ids = [$id];
}
if (!is_array($ids)) {
throw new BadRequest("No `ids`.");
}
$this->inboxService->markAsImportantIdList($ids);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,65 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Email\InboxService;
/**
* Moves emails to trash.
*/
class PostInboxInTrash implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$ids = $data->ids ?? null;
$id = $data->id ?? null;
if ($ids === null && is_string($id)) {
$ids = [$id];
}
if (!is_array($ids)) {
throw new BadRequest("No `ids`.");
}
$this->inboxService->moveToTrashIdList($ids);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Email\InboxService;
/**
* Marks emails as read.
*/
class PostInboxRead implements Action
{
public function __construct(private InboxService $inboxService) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
if (!empty($data->all)) {
$this->inboxService->markAllAsRead();
return ResponseComposer::json(true);
}
$ids = $data->ids ?? null;
$id = $data->id ?? null;
if ($ids === null && is_string($id)) {
$ids = [$id];
}
if (!is_array($ids)) {
throw new BadRequest("No `ids`.");
}
$this->inboxService->markAsReadIdList($ids);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,118 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Acl;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Mail\Exceptions\NoSmtp;
use Espo\Core\Mail\SmtpParams;
use Espo\Entities\Email;
use Espo\Tools\Email\SendService;
use Espo\Tools\Email\TestSendData;
/**
* Sends test emails.
*/
class PostSendTest implements Action
{
public function __construct(
private SendService $sendService,
private Acl $acl
) {}
/**
* @throws BadRequest
* @throws Forbidden
* @throws Error
* @throws NoSmtp
* @throws NotFound
*/
public function process(Request $request): Response
{
if (!$this->acl->checkScope(Email::ENTITY_TYPE)) {
throw new Forbidden();
}
$data = $request->getParsedBody();
$type = $data->type ?? null;
$id = $data->id ?? null;
$server = $data->server ?? null;
$port = $data->port ?? null;
$username = $data->username ?? null;
$password = $data->password ?? null;
$auth = $data->auth ?? null;
$authMechanism = $data->authMechanism ?? null;
$security = $data->security ?? null;
$userId = $data->userId ?? null;
$fromAddress = $data->fromAddress ?? null;
$fromName = $data->fromName ?? null;
$emailAddress = $data->emailAddress ?? null;
if (!is_string($server)) {
throw new BadRequest("No `server`");
}
if (!is_int($port)) {
throw new BadRequest("No or bad `port`.");
}
if (!is_string($emailAddress)) {
throw new BadRequest("No `emailAddress`.");
}
$smtpParams = SmtpParams
::create($server, $port)
->withSecurity($security)
->withFromName($fromName)
->withFromAddress($fromAddress)
->withAuth($auth);
if ($auth) {
$smtpParams = $smtpParams
->withUsername($username)
->withPassword($password)
->withAuthMechanism($authMechanism);
}
$data = new TestSendData($emailAddress, $type, $id, $userId);
$this->sendService->sendTestEmail($smtpParams, $data);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,177 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email\Api;
use Espo\Core\Acl;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Field\LinkParent;
use Espo\Core\Notification\UserEnabledChecker;
use Espo\Core\Record\EntityProvider;
use Espo\Entities\Email;
use Espo\Entities\Notification;
use Espo\Entities\User;
use Espo\ORM\EntityManager;
use Espo\ORM\Name\Attribute;
use RuntimeException;
/**
* @noinspection PhpUnused
*/
class PostUsers implements Action
{
public function __construct(
private EntityProvider $entityProvider,
private Acl $acl,
private EntityManager $entityManager,
private UserEnabledChecker $userEnabledChecker,
private User $user,
) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id') ?? throw new RuntimeException();
$data = $request->getParsedBody();
$email = $this->getEmail($id);
$foreignIds = [];
if (isset($data->id)) {
$foreignIds[] = $data->id;
}
if (isset($data->ids) && is_array($data->ids)) {
foreach ($data->ids as $foreignId) {
$foreignIds[] = $foreignId;
}
}
foreach ($foreignIds as $foreignId) {
if (!is_string($foreignId)) {
throw new BadRequest("Bad ID.");
}
}
$relation = $this->entityManager->getRelation($email, 'users');
foreach ($this->getUsers($foreignIds) as $user) {
if ($relation->isRelated($user)) {
continue;
}
$relation->relate($user);
if ($this->user->getId() === $user->getId()) {
continue;
}
$this->processNotify($email, $user);
}
return ResponseComposer::json(true);
}
/**
* @throws Forbidden
* @throws NotFound
*/
private function getEmail(string $id): Email
{
$email = $this->entityProvider->getByClass(Email::class, $id);
if (!$this->acl->checkEntityEdit($email)) {
throw new Forbidden("No edit access to email.");
}
return $email;
}
/**
* @param string[] $foreignIds
* @return User[]
* @throws Forbidden
* @throws NotFound
*/
private function getUsers(array $foreignIds): iterable
{
/** @var iterable<User> $users */
$users = $this->entityManager
->getRDBRepositoryByClass(User::class)
->where([Attribute::ID => $foreignIds])
->find();
if (is_countable($users) && count($users) !== count($foreignIds)) {
throw new NotFound("Users not found.");
}
foreach ($users as $user) {
if (!$this->acl->checkAssignmentPermission($user)) {
throw new Forbidden("No assignment permission to user.");
}
if (!$this->acl->checkEntityRead($user)) {
throw new Forbidden("No access to user.");
}
if (!$user->isRegular() && !$user->isAdmin()) {
throw new Forbidden("Only regular and admin users allowed.");
}
}
return $users;
}
private function processNotify(Email $email, User $user): void
{
if (!$this->userEnabledChecker->checkAssignment(Email::ENTITY_TYPE, $user->getId())) {
return;
}
$notification = $this->entityManager->getRDBRepositoryByClass(Notification::class)->getNew();
$notification
->setType('EmailInbox')
->setRelated(LinkParent::createFromEntity($email))
->setUserId($user->getId())
->setData([
'emailName' => $email->getSubject(),
'userId' => $this->user->getId(),
'userName' => $this->user->getName(),
]);
$this->entityManager->saveEntity($notification);
}
}

View File

@@ -0,0 +1,69 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
use Espo\Core\Field\EmailAddress;
use Espo\Core\Name\Field;
use Espo\ORM\Entity;
use stdClass;
class EmailAddressEntityPair
{
private EmailAddress $emailAddress;
private Entity $entity;
public function __construct(
EmailAddress $emailAddress,
Entity $entity
) {
$this->emailAddress = $emailAddress;
$this->entity = $entity;
}
public function getEmailAddress(): EmailAddress
{
return $this->emailAddress;
}
public function getEntity(): Entity
{
return $this->entity;
}
public function getValueMap(): stdClass
{
return (object) [
'emailAddress' => $this->emailAddress->getAddress(),
'name' => $this->entity->get(Field::NAME),
'entityId' => $this->entity->getId(),
'entityType' => $this->entity->getEntityType(),
];
}
}

View File

@@ -0,0 +1,41 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
class Folder
{
public const ALL = 'all';
public const INBOX = 'inbox';
public const SENT = 'sent';
public const DRAFTS = 'drafts';
public const IMPORTANT = 'important';
public const ARCHIVE = 'archive';
public const TRASH = 'trash';
}

View File

@@ -0,0 +1,132 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
use Espo\Core\Exceptions\Conflict;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\FileStorage\Manager;
use Espo\Core\Mail\Importer;
use Espo\Core\Mail\Importer\Data;
use Espo\Core\Mail\MessageWrapper;
use Espo\Core\Mail\Parsers\MailMimeParser;
use Espo\Entities\Attachment;
use Espo\Entities\Email;
use Espo\ORM\EntityManager;
class ImportEmlService
{
public function __construct(
private Importer $importer,
private Importer\DuplicateFinder $duplicateFinder,
private EntityManager $entityManager,
private Manager $fileStorageManager,
private MailMimeParser $parser,
) {}
/**
* Import an EML.
*
* @param string $fileId An attachment ID.
* @param ?string $userId A user ID to relate an email with.
* @return Email An Email.
* @throws NotFound
* @throws Error
* @throws Conflict
*/
public function import(string $fileId, ?string $userId = null): Email
{
$attachment = $this->getAttachment($fileId);
$contents = $this->fileStorageManager->getContents($attachment);
$message = new MessageWrapper(1, null, $this->parser, $contents);
$this->checkDuplicate($message);
$email = $this->importer->import($message, Data::create());
if (!$email) {
throw new Error("Could not import.");
}
if ($userId) {
$this->entityManager->getRDBRepositoryByClass(Email::class)
->getRelation($email, 'users')
->relateById($userId);
}
$this->entityManager->removeEntity($attachment);
return $email;
}
/**
* @throws NotFound
*/
private function getAttachment(string $fileId): Attachment
{
$attachment = $this->entityManager->getRDBRepositoryByClass(Attachment::class)->getById($fileId);
if (!$attachment) {
throw new NotFound("Attachment not found.");
}
return $attachment;
}
/**
* @throws Conflict
*/
private function checkDuplicate(MessageWrapper $message): void
{
$messageId = $this->parser->getMessageId($message);
if (!$messageId) {
return;
}
$email = $this->entityManager->getRDBRepositoryByClass(Email::class)->getNew();
$email->setMessageId($messageId);
$duplicate = $this->duplicateFinder->find($email, $message);
if (!$duplicate) {
return;
}
throw Conflict::createWithBody(
'Email is already imported.',
Error\Body::create()->withMessageTranslation('alreadyImported', Email::ENTITY_TYPE, [
'id' => $duplicate->getId(),
'link' => '#Email/view/' . $duplicate->getId(),
])
);
}
}

View File

@@ -0,0 +1,719 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
use Espo\Core\AclManager;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error\Body;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Name\Field;
use Espo\Core\Select\SelectBuilderFactory;
use Espo\Core\Select\Where\Item as WhereItem;
use Espo\Core\Utils\Log;
use Espo\Core\WebSocket\Submission as WebSocketSubmission;
use Espo\Entities\Email;
use Espo\Entities\EmailFolder;
use Espo\Entities\GroupEmailFolder;
use Espo\Entities\Notification;
use Espo\Entities\Team;
use Espo\Entities\User;
use Espo\ORM\EntityManager;
use Espo\ORM\Name\Attribute;
use Espo\ORM\Query\Part\Condition;
use Espo\ORM\Query\Part\Expression;
use Espo\ORM\Query\SelectBuilder;
use Exception;
use RuntimeException;
class InboxService
{
public function __construct(
private User $user,
private EntityManager $entityManager,
private AclManager $aclManager,
private Log $log,
private SelectBuilderFactory $selectBuilderFactory,
private WebSocketSubmission $webSocketSubmission,
) {}
/**
* @param string[] $idList
*/
public function moveToFolderIdList(array $idList, ?string $folderId, ?string $userId = null): void
{
foreach ($idList as $id) {
try {
$this->moveToFolder($id, $folderId, $userId);
} catch (Exception) {}
}
}
/**
* @throws Forbidden
* @throws NotFound
*/
public function moveToFolder(string $id, ?string $folderId, ?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
if ($folderId === Folder::INBOX) {
$folderId = null;
}
$email = $this->getEmail($id);
$user = $this->getUser($userId);
if ($email->getGroupFolder()) {
$this->checkCurrentGroupFolder($email->getGroupFolder()->getId(), $user);
}
if ($folderId && str_starts_with($folderId, 'group:')) {
try {
$this->moveToGroupFolder($email, substr($folderId, 6), $user);
} catch (Exception $e) {
$this->log->debug("Could not move email to group folder. {message}", ['message' => $e->getMessage()]);
throw $e;
}
return;
}
if ($folderId === Folder::ARCHIVE) {
$this->moveToArchive($email, $user);
return;
}
if ($email->getGroupFolder()) {
if (!$this->aclManager->checkEntityEdit($user, $email)) {
throw Forbidden::createWithBody(
"Cannot move out from group folder. No edit access to email.",
Body::create()->withMessageTranslation('groupMoveOutNoEditAccess', 'Email')
);
}
$email
->setGroupFolder(null)
->setGroupStatusFolder(null);
$this->entityManager->saveEntity($email);
}
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set([
'folderId' => $folderId,
'inTrash' => false,
'inArchive' => false,
])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'emailId' => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
}
/**
* @throws Forbidden
* @throws NotFound
*/
private function moveToGroupFolder(Email $email, string $folderId, User $user): void
{
$folder = $this->getGroupFolder($folderId);
if (!$this->aclManager->checkEntityRead($user, $folder)) {
throw new Forbidden("Cannot move to group folder. No access to folder.");
}
if (!$this->aclManager->checkEntityEdit($user, $email)) {
throw Forbidden::createWithBody(
"Cannot move to group folder. No edit access to email.",
Body::create()->withMessageTranslation('groupMoveToNoEditAccess', 'Email')
);
}
$email
->setGroupFolder($folder)
->setGroupStatusFolder(null);
$this->applyGroupFolder($email, $folder);
$this->entityManager->saveEntity($email);
$this->retrieveFromArchive($email, $user);
}
/**
* @param string[] $idList
*/
public function moveToTrashIdList(array $idList, ?string $userId = null): bool
{
foreach ($idList as $id) {
try {
$this->moveToTrash($id, $userId);
} catch (Exception) {}
}
return true;
}
/**
* @param string[] $idList
*/
public function retrieveFromTrashIdList(array $idList, ?string $userId = null): void
{
foreach ($idList as $id) {
try {
$this->retrieveFromTrash($id, $userId);
} catch (Exception) {}
}
}
/**
* @throws NotFound
* @throws Forbidden
*/
public function moveToTrash(string $id, ?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
$email = $this->getEmail($id);
$user = $this->getUser($userId);
if ($email->getGroupFolder()) {
$folder = $this->getGroupFolder($email->getGroupFolder()->getId());
if (!$this->aclManager->checkEntityRead($user, $folder)) {
throw Forbidden::createWithBody(
"Cannot move email from group folder to trash. No access to group folder.",
Body::create()->withMessageTranslation('groupFolderNoAccess', 'Email')
);
}
if (!$this->aclManager->checkEntityEdit($user, $email)) {
throw Forbidden::createWithBody(
"Cannot move email from group folder to trash.",
Body::create()->withMessageTranslation('groupMoveToTrashNoEditAccess', 'Email')
);
}
$email->setGroupStatusFolder(Email::GROUP_STATUS_FOLDER_TRASH);
$this->entityManager->saveEntity($email);
return;
}
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set(['inTrash' => true])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'emailId' => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
$this->markNotificationAsRead($id, $userId);
}
/**
* @throws Forbidden
* @throws NotFound
*/
public function retrieveFromTrash(string $id, ?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
$email = $this->getEmail($id);
$user = $this->getUser($userId);
if ($email->getGroupFolder()) {
$folder = $this->getGroupFolder($email->getGroupFolder()->getId());
if (!$this->aclManager->checkEntityEdit($user, $email)) {
throw Forbidden::createWithBody(
"Cannot retrieve group folder email from trash. No edit to email.",
Body::create()->withMessageTranslation('notEditAccess', 'Email')
);
}
if (!$this->aclManager->checkEntityRead($user, $folder)) {
throw Forbidden::createWithBody(
"Cannot retrieve group folder email from trash. No access to group folder.",
Body::create()->withMessageTranslation('groupFolderNoAccess', 'Email')
);
}
$email->setGroupStatusFolder(null);
$this->entityManager->saveEntity($email);
return;
}
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set(['inTrash' => false])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'emailId' => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
}
/**
* @param string[] $idList
*/
public function markAsReadIdList(array $idList, ?string $userId = null): void
{
foreach ($idList as $id) {
$this->markAsRead($id, $userId);
}
}
/**
* @param string[] $idList
*/
public function markAsNotReadIdList(array $idList, ?string $userId = null): void
{
foreach ($idList as $id) {
$this->markAsNotRead($id, $userId);
}
}
public function markAsRead(string $id, ?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set(['isRead' => true])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'emailId' => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
$this->markNotificationAsRead($id, $userId);
}
public function markAsNotRead(string $id, ?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set(['isRead' => false])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'emailId' => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
}
/**
* @param string[] $idList
*/
public function markAsImportantIdList(array $idList, ?string $userId = null): void
{
foreach ($idList as $id) {
$this->markAsImportant($id, $userId);
}
}
/**
* @param string[] $idList
*/
public function markAsNotImportantIdList(array $idList, ?string $userId = null): void
{
foreach ($idList as $id) {
$this->markAsNotImportant($id, $userId);
}
}
public function markAsImportant(string $id, ?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set(['isImportant' => true])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'emailId' => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
}
public function markAsNotImportant(string $id, ?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set(['isImportant' => false])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'emailId' => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
}
public function markAllAsRead(?string $userId = null): void
{
$userId = $userId ?? $this->user->getId();
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set(['isRead' => true])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'isRead' => false,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
$update = $this
->entityManager
->getQueryBuilder()
->update()
->in(Notification::ENTITY_TYPE)
->set(['read' => true])
->where([
Attribute::DELETED => false,
'userId' => $userId,
'relatedType' => Email::ENTITY_TYPE,
'read' => false,
'type' => Notification::TYPE_EMAIL_RECEIVED,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
$this->submitNotificationWebSocket($userId);
}
public function markNotificationAsRead(string $id, string $userId): void
{
$notification = $this->entityManager
->getRDBRepositoryByClass(Notification::class)
->where([
'userId' => $userId,
'relatedType' => Email::ENTITY_TYPE,
'relatedId' => $id,
'read' => false,
'type' => Notification::TYPE_EMAIL_RECEIVED,
])
->findOne();
if (!$notification) {
return;
}
$notification->setRead();
$this->entityManager->saveEntity($notification);
$this->submitNotificationWebSocket($userId);
}
private function submitNotificationWebSocket(string $userId): void
{
$this->webSocketSubmission->submit('newNotification', $userId);
}
/**
* @return array<string, int>
*/
public function getFoldersNotReadCounts(): array
{
$data = [];
$selectBuilder = $this->selectBuilderFactory
->create()
->from(Email::ENTITY_TYPE)
->withAccessControlFilter();
$draftsSelectBuilder = clone $selectBuilder;
$selectBuilder->withWhere(
WhereItem::fromRaw([
'type' => 'isTrue',
'attribute' => 'isNotRead',
])
);
$folderIdList = [Folder::INBOX, Folder::DRAFTS];
$emailFolderList = $this->entityManager
->getRDBRepository(EmailFolder::ENTITY_TYPE)
->where([
'assignedUserId' => $this->user->getId(),
])
->find();
foreach ($emailFolderList as $folder) {
$folderIdList[] = $folder->getId();
}
$groupFolderList = $this->entityManager
->getRDBRepositoryByClass(GroupEmailFolder::class)
->distinct()
->leftJoin(Field::TEAMS)
->where(
$this->user->isAdmin() ?
['id!=' => null] :
['teams.id' => $this->user->getTeamIdList()]
)
->find();
foreach ($groupFolderList as $folder) {
$folderIdList[] = 'group:' . $folder->getId();
}
foreach ($folderIdList as $folderId) {
$itemSelectBuilder = clone $selectBuilder;
if ($folderId === Folder::DRAFTS) {
$itemSelectBuilder = clone $draftsSelectBuilder;
}
$itemSelectBuilder->withWhere(
WhereItem::fromRaw([
'type' => 'inFolder',
'attribute' => 'folderId',
'value' => $folderId,
])
);
try {
$data[$folderId] = $this->entityManager
->getRDBRepository(Email::ENTITY_TYPE)
->clone($itemSelectBuilder->build())
->count();
} catch (BadRequest|Forbidden $e) {
throw new RuntimeException($e->getMessage());
}
}
return $data;
}
/**
* @throws Forbidden
*/
public function moveToArchive(Email $email, User $user): void
{
if (!$this->aclManager->checkEntityRead($user, $email)) {
throw new Forbidden("No read access to email.");
}
if ($email->getGroupFolder()) {
if (!$this->aclManager->checkEntityEdit($user, $email)) {
throw Forbidden::createWithBody(
"Cannot move from group folder to Archive. No edit access to email.",
Body::create()->withMessageTranslation('groupMoveToArchiveNoEditAccess', 'Email')
);
}
$email->setGroupStatusFolder(Email::GROUP_STATUS_FOLDER_ARCHIVE);
$this->entityManager->saveEntity($email);
return;
}
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set([
'folderId' => null,
'inArchive' => true,
'inTrash' => false,
])
->where([
Attribute::DELETED => false,
'userId' => $user->getId(),
'emailId' => $email->getId(),
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
}
public function retrieveFromArchive(Email $email, User $user): void
{
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Email::RELATIONSHIP_EMAIL_USER)
->set([
'folderId' => null,
'inArchive' => false,
])
->where([
Attribute::DELETED => false,
'userId' => $user->getId(),
'emailId' => $email->getId(),
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
}
/**
* @throws Forbidden
*/
private function checkCurrentGroupFolder(string $folderId, User $user): void
{
$folder = $this->entityManager->getEntityById(GroupEmailFolder::ENTITY_TYPE, $folderId);
if ($folder && !$this->aclManager->checkEntityRead($user, $folder)) {
throw new Forbidden("No access to current group folder.");
}
}
/**
* @throws NotFound
*/
private function getUser(string $userId): User
{
$user = $userId === $this->user->getId() ?
$this->user :
$this->entityManager->getRDBRepositoryByClass(User::class)->getById($userId);
if (!$user) {
throw new NotFound("User not found.");
}
return $user;
}
/**
* @throws NotFound
*/
private function getEmail(string $id): Email
{
$email = $this->entityManager->getRDBRepositoryByClass(Email::class)->getById($id);
if (!$email) {
throw new NotFound();
}
return $email;
}
/**
* @throws NotFound
*/
private function getGroupFolder(string $folderId): GroupEmailFolder
{
$folder = $this->entityManager->getRDBRepositoryByClass(GroupEmailFolder::class)->getById($folderId);
if (!$folder) {
throw new NotFound("Group folder not found.");
}
return $folder;
}
private function applyGroupFolder(Email $email, GroupEmailFolder $folder): void
{
if (!$folder->getTeams()->getCount()) {
return;
}
foreach ($folder->getTeams()->getIdList() as $teamId) {
$email->addTeamId($teamId);
}
$users = $this->entityManager
->getRDBRepositoryByClass(User::class)
->select([Attribute::ID])
->where([
'type' => [User::TYPE_REGULAR, User::TYPE_ADMIN],
'isActive' => true,
])
->where(
Condition::in(
Expression::column(Attribute::ID),
SelectBuilder::create()
->from(Team::RELATIONSHIP_TEAM_USER)
->select('userId')
->where(['teamId' => $folder->getTeams()->getIdList()])
->build()
)
)
->find();
foreach ($users as $user) {
$email->addUserId($user->getId());
}
}
}

View File

@@ -0,0 +1,604 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
use Espo\Core\Acl;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\ErrorSilent;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\FieldValidation\FieldValidationManager;
use Espo\Core\Mail\Account\Account;
use Espo\Core\Mail\Account\GroupAccount\Account as GroupAccount;
use Espo\Core\Mail\Account\GroupAccount\AccountFactory as GroupAccountFactory;
use Espo\Core\Mail\Account\GroupAccount\Service as GroupAccountService;
use Espo\Core\Mail\Account\PersonalAccount\Account as PersonalAccount;
use Espo\Core\Mail\Account\PersonalAccount\AccountFactory as PersonalAccountFactory;
use Espo\Core\Mail\Account\PersonalAccount\Service as PersonalAccountService;
use Espo\Core\Mail\Account\SendingAccountProvider;
use Espo\Core\Mail\ConfigDataProvider;
use Espo\Core\Mail\EmailSender;
use Espo\Core\Mail\Exceptions\NoSmtp;
use Espo\Core\Mail\Exceptions\SendingError;
use Espo\Core\Mail\Sender;
use Espo\Core\Mail\SenderParams;
use Espo\Core\Mail\Smtp\HandlerProcessor;
use Espo\Core\Mail\SmtpParams;
use Espo\Core\Name\Link;
use Espo\Core\ORM\Repository\Option\SaveOption;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Json;
use Espo\Core\Utils\Log;
use Espo\Entities\Email;
use Espo\Entities\EmailAccount;
use Espo\Entities\EmailAddress;
use Espo\Entities\InboundEmail;
use Espo\Entities\User;
use Espo\Modules\Crm\Entities\CaseObj;
use Espo\ORM\Collection;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use Espo\Tools\Stream\Service as StreamService;
use Exception;
use LogicException;
use const FILTER_VALIDATE_EMAIL;
/**
* Email sending service.
*/
class SendService
{
private const LINK_EMAIL_ADDRESSES = Link::EMAIL_ADDRESSES;
/** @var string[] */
private array $notAllowedStatusList = [
Email::STATUS_ARCHIVED,
Email::STATUS_SENT,
Email::STATUS_BEING_IMPORTED,
];
public function __construct(
private User $user,
private EntityManager $entityManager,
private FieldValidationManager $fieldValidationManager,
private EmailSender $emailSender,
private StreamService $streamService,
private Config $config,
private Log $log,
private Acl $acl,
private SendingAccountProvider $accountProvider,
private PersonalAccountService $personalAccountService,
private GroupAccountService $groupAccountService,
private HandlerProcessor $handlerProcessor,
private PersonalAccountFactory $personalAccountFactory,
private GroupAccountFactory $groupAccountFactory,
private ConfigDataProvider $configDataProvider,
) {}
/**
* Send an email entity.
*
* @params Email $entity An email entity.
* @params ?User $user A user from what to send.
*
* @throws BadRequest If not valid.
* @throws SendingError On error while sending.
* @throws NoSmtp No SMTP settings.
* @throws Error An error.
*/
public function send(Email $entity, ?User $user = null): void
{
if (in_array($entity->getStatus(), $this->notAllowedStatusList)) {
throw new Error("Can't send email with status `{$entity->getStatus()}`.");
}
if (!$this->fieldValidationManager->check($entity, 'to', 'required')) {
$entity->setStatus(Email::STATUS_DRAFT);
$this->entityManager->saveEntity($entity, [SaveOption::SILENT => true]);
throw new BadRequest("Empty To address.");
}
$systemIsShared = $this->configDataProvider->isSystemOutboundAddressShared();
$systemFromName = $this->config->get('outboundEmailFromName');
$systemFromAddress = $this->configDataProvider->getSystemOutboundAddress();
$sender = $this->emailSender->create();
$userAddressList = [];
if ($user) {
// @todo Use getEmailAddressGroup.
/** @var Collection<EmailAddress> $emailAddressCollection */
$emailAddressCollection = $this->entityManager
->getRelation($user, self::LINK_EMAIL_ADDRESSES)
->find();
foreach ($emailAddressCollection as $ea) {
$userAddressList[] = $ea->getLower();
}
}
$originalFromAddress = $entity->getFromAddress();
if (!$originalFromAddress) {
throw new Error("Email sending: Can't send with empty 'from' address.");
}
$fromAddress = strtolower($originalFromAddress);
$isUserAddress = in_array($fromAddress, $userAddressList);
$isSystemAddress = $fromAddress === strtolower($systemFromAddress ?? '');
$smtpParams = null;
$personalAccount = null;
$groupAccount = null;
$params = SenderParams::create();
if ($user && $isUserAddress) {
[$smtpParams, $personalAccount] = $this->getPersonalAccount($user, $originalFromAddress);
}
if ($user && $smtpParams) {
$sender->withSmtpParams($smtpParams);
}
if (!$smtpParams) {
[$smtpParams, $groupAccount] = $this->getGroupAccount($user, $originalFromAddress);
if ($smtpParams) {
$sender->withSmtpParams($smtpParams);
}
}
if (!$smtpParams && $isSystemAddress) {
$params = $params->withFromName($systemFromName);
}
// Otherwise, allow users to send from the system SMTP with their own from-address.
if (!$smtpParams && !$systemIsShared) {
if ($isSystemAddress) {
throw new NoSmtp("Can not use system SMTP. System SMTP is not shared.");
}
throw new NoSmtp("No SMTP params for $fromAddress.");
}
if (
!$smtpParams &&
$user &&
in_array($fromAddress, $userAddressList)
) {
$params = $params->withFromName($user->getName());
}
$parent = null;
$parentId = $entity->getParentId();
$parentType = $entity->getParentType();
if ($parentType && $parentId) {
$parent = $this->entityManager->getEntityById($parentType, $parentId);
$params = $this->applyParent($parent, $params);
}
$this->validateEmailAddresses($entity);
$messageContainer = new Sender\MessageContainer();
if (
$groupAccount instanceof GroupAccount && $groupAccount->storeSentEmails() ||
$personalAccount instanceof PersonalAccount && $personalAccount->storeSentEmails()
) {
$sender->withMessageContainer($messageContainer);
}
$this->applyReplied($entity, $sender);
$sender->withParams($params);
try {
$sender->send($entity);
} catch (Exception $e) {
$entity->setStatus(Email::STATUS_DRAFT);
$this->entityManager->saveEntity($entity, [SaveOption::SILENT => true]);
$this->log->error("Email sending: " . $e->getMessage(), ['exception' => $e]);
$errorData = [
'id' => $entity->getId(),
'message' => $e->getMessage(),
];
throw ErrorSilent::createWithBody('sendingFail', Json::encode($errorData));
}
if ($groupAccount) {
$groupAccountId = $groupAccount->getId();
if ($groupAccountId) {
$entity->addLinkMultipleId('inboundEmails', $groupAccountId);
}
}
if ($personalAccount) {
$personalAccountId = $personalAccount->getId();
if ($personalAccountId) {
$entity->addLinkMultipleId('emailAccounts', $personalAccountId);
}
}
$this->entityManager->saveEntity($entity, [Email::SAVE_OPTION_IS_JUST_SENT => true]);
$this->store($messageContainer, $groupAccount, $personalAccount);
if ($parent) {
$this->streamService->noteEmailSent($parent, $entity);
}
}
private function applyParent(?Entity $parent, SenderParams $params): SenderParams
{
// @todo Refactor. Move to a separate class? Make extensible?
if ($parent instanceof CaseObj) {
$inboundEmailId = $parent->getInboundEmailId();
if (!$inboundEmailId) {
return $params;
}
$inboundEmail = $this->entityManager
->getRDBRepositoryByClass(InboundEmail::class)
->getById($inboundEmailId);
if (!$inboundEmail || !$inboundEmail->getReplyToAddress()) {
return $params;
}
$params = $params->withReplyToAddress($inboundEmail->getReplyToAddress());
}
return $params;
}
private function store(
Sender\MessageContainer $messageContainer,
?Account $groupAccount,
?Account $personalAccount,
): void {
$message = $messageContainer->message;
if (!$message) {
return;
}
if ($groupAccount instanceof GroupAccount && $groupAccount->storeSentEmails()) {
$id = $groupAccount->getId() ?? null;
if (!$id) {
throw new LogicException();
}
try {
$this->groupAccountService->storeSentMessage($id, $message);
} catch (Exception $e) {
$text = "Could not store sent email; group account {$groupAccount->getId()}); " .
$e->getMessage() . ".";
$this->log->error($text, ['exception' => $e]);
}
}
if ($personalAccount instanceof PersonalAccount && $personalAccount->storeSentEmails()) {
$id = $personalAccount->getId() ?? null;
if (!$id) {
throw new LogicException();
}
try {
$this->personalAccountService->storeSentMessage($id, $message);
} catch (Exception $e) {
$text = "Could not store sent email; personal account {$personalAccount->getId()}; " .
$e->getMessage() . ".";
$this->log->error($text, ['exception' => $e]);
}
}
}
/**
* @return array{?SmtpParams, ?Account}
*/
private function getPersonalAccount(User $user, string $emailAddress): array
{
$personalAccount = $this->accountProvider->getPersonal($user, $emailAddress);
if (!$personalAccount) {
return [null, null];
}
if (!$personalAccount->isAvailableForSending()) {
return [null, null];
}
$smtpParams = $personalAccount->getSmtpParams();
if (!$smtpParams) {
return [null, null];
}
$smtpParams = $smtpParams->withFromName($user->getName());
return [$smtpParams, $personalAccount];
}
/**
* @return array{?SmtpParams, ?Account}
*/
private function getGroupAccount(?User $user, string $emailAddress): array
{
$groupAccount = $user ?
$this->accountProvider->getShared($user, $emailAddress) :
$this->accountProvider->getGroup($emailAddress);
if (!$groupAccount) {
return [null, null];
}
$smtpParams = $groupAccount->getSmtpParams();
if (!$smtpParams) {
return [null, null];
}
return [$smtpParams, $groupAccount];
}
/**
* @throws Forbidden
* @throws Error
* @throws NotFound
* @throws NoSmtp
*/
public function sendTestEmail(SmtpParams $params, TestSendData $data): void
{
$emailAddress = $data->getEmailAddress();
$userId = $data->getUserId();
$type = $data->getType();
$id = $data->getId();
if ($params->getPassword() === null) {
$params = $params->withPassword(
$this->obtainSendTestEmailPassword($type, $id)
);
}
if (
$userId &&
$userId !== $this->user->getId() &&
!$this->user->isAdmin()
) {
throw new Forbidden();
}
/** @var ?User $user */
$user = $userId ?
$this->entityManager->getRDBRepositoryByClass(User::class)->getById($userId) :
null;
if ($userId && !$user) {
throw new NotFound("User not found.");
}
/** @var Email $email */
$email = $this->entityManager->getNewEntity(Email::ENTITY_TYPE);
$email
->setSubject('EspoCRM: Test Email')
->setIsHtml(false)
->addToAddress($emailAddress);
$handlerClassName = null;
if ($type === 'emailAccount' && $id) {
/** @var ?EmailAccount $emailAccount */
$emailAccount = $this->entityManager->getEntityById(EmailAccount::ENTITY_TYPE, $id);
$handlerClassName = $emailAccount?->getSmtpHandlerClassName();
}
if ($type === 'inboundEmail' && $id) {
/** @var ?InboundEmail $inboundEmail */
$inboundEmail = $this->entityManager->getEntityById(InboundEmail::ENTITY_TYPE, $id);
if ($inboundEmail) {
$handlerClassName = $inboundEmail->getSmtpHandlerClassName();
}
}
if ($handlerClassName && $id) {
$params = $this->handlerProcessor->handle($handlerClassName, $params, $id);
}
try {
$this->emailSender
->withSmtpParams($params)
->send($email);
} catch (Exception $e) {
$this->log->warning("Email sending:" . $e->getMessage() . "; " . $e->getCode());
if ($e instanceof SendingError) {
throw ErrorSilent::createWithBody(
'sendingFail',
Error\Body::create()
->withMessageTranslation($e->getMessage(), Email::ENTITY_TYPE)
);
}
$errorData = ['message' => $e->getMessage()];
throw ErrorSilent::createWithBody('sendingFail', Json::encode($errorData));
}
}
/**
* @throws Error
*/
public function validateEmailAddresses(Email $entity): void
{
$from = $entity->getFromAddress();
if ($from) {
if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
throw new Error('From email address is not valid.');
}
}
foreach ($entity->getToAddressList() as $address) {
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
throw new Error('To email address is not valid.');
}
}
foreach ($entity->getCcAddressList() as $address) {
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
throw new Error('CC email address is not valid.');
}
}
foreach ($entity->getBccAddressList() as $address) {
if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
throw new Error('BCC email address is not valid.');
}
}
}
/**
* Get a user personal SMTP params.
*/
public function getUserSmtpParams(string $userId): ?SmtpParams
{
/** @var ?User $user */
$user = $this->entityManager->getRDBRepositoryByClass(User::class)->getById($userId);
if (!$user) {
return null;
}
$address = $user->getEmailAddress();
if (!$address) {
return null;
}
$account = $this->accountProvider->getPersonal($user, $address);
if (!$account) {
return null;
}
$smtpParams = $account->getSmtpParams();
return $smtpParams
?->withFromName($user->getName())
->withFromAddress($address);
}
/**
* @throws Forbidden
* @throws Error
* @throws NoSmtp
*/
private function obtainSendTestEmailPassword(?string $type, ?string $id): ?string
{
if ($type === 'emailAccount') {
if (!$this->acl->checkScope(EmailAccount::ENTITY_TYPE)) {
throw new Forbidden();
}
if (!$id) {
return null;
}
$personalAccount = $this->personalAccountFactory->create($id);
if (
!$this->user->isAdmin() &&
$personalAccount->getUser()->getId() !== $this->user->getId()
) {
throw new Forbidden();
}
$smtpParams = $personalAccount->getSmtpParams();
return $smtpParams?->getPassword();
}
if (!$this->user->isAdmin()) {
throw new Forbidden();
}
if ($type === 'inboundEmail') {
if (!$id) {
return null;
}
$smtpParams = $this->groupAccountFactory
->create($id)
->getSmtpParams();
return $smtpParams?->getPassword();
}
return $this->config->get('smtpPassword');
}
private function applyReplied(Email $entity, Sender $sender): void
{
$replied = $entity->getReplied();
if ($replied && $replied->getMessageId()) {
$sender->withAddedHeader('In-Reply-To', $replied->getMessageId());
$sender->withAddedHeader('References', $replied->getMessageId());
}
if ($replied && $replied->getGroupFolder()) {
$entity->setGroupFolder($replied->getGroupFolder());
}
}
}

View File

@@ -0,0 +1,119 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Record\ServiceContainer;
use Espo\Entities\Attachment;
use Espo\Entities\Email;
use Espo\ORM\EntityManager;
use Espo\Repositories\Attachment as AttachmentRepository;
use Espo\Tools\Attachment\AccessChecker as AttachmentAccessChecker;
use Espo\Tools\Attachment\FieldData;
class Service
{
private EntityManager $entityManager;
private AttachmentAccessChecker $attachmentAccessChecker;
private ServiceContainer $serviceContainer;
public function __construct(
EntityManager $entityManager,
AttachmentAccessChecker $attachmentAccessChecker,
ServiceContainer $serviceContainer
) {
$this->entityManager = $entityManager;
$this->attachmentAccessChecker = $attachmentAccessChecker;
$this->serviceContainer = $serviceContainer;
}
/**
* Copy email attachments for re-using (e.g. in a forward email).
*
* @return Attachment[]
* @throws NotFound
* @throws Forbidden
*/
public function copyAttachments(string $id, FieldData $fieldData): array
{
/** @var ?Email $entity */
$entity = $this->serviceContainer
->get(Email::ENTITY_TYPE)
->getEntity($id);
if (!$entity) {
throw new NotFound();
}
$this->attachmentAccessChecker->check($fieldData);
$list = [];
foreach ($entity->getAttachmentIdList() as $attachmentId) {
$attachment = $this->copyAttachment($attachmentId, $fieldData);
if ($attachment) {
$list[] = $attachment;
}
}
return $list;
}
private function copyAttachment(string $attachmentId, FieldData $fieldData): ?Attachment
{
/** @var ?Attachment $attachment */
$attachment = $this->entityManager
->getRDBRepositoryByClass(Attachment::class)
->getById($attachmentId);
if (!$attachment) {
return null;
}
$copied = $this->getAttachmentRepository()->getCopiedAttachment($attachment);
$copied->set('parentType', $fieldData->getParentType());
$copied->set('relatedType', $fieldData->getRelatedType());
$copied->setTargetField($fieldData->getField());
$copied->setRole(Attachment::ROLE_ATTACHMENT);
$this->getAttachmentRepository()->save($copied);
return $copied;
}
private function getAttachmentRepository(): AttachmentRepository
{
/** @var AttachmentRepository */
return $this->entityManager->getRepositoryByClass(Attachment::class);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
class TestSendData
{
private string $emailAddress;
private ?string $type;
private ?string $id;
private ?string $userId;
public function __construct(
string $emailAddress,
?string $type,
?string $id,
?string $userId
) {
$this->emailAddress = $emailAddress;
$this->type = $type;
$this->id = $id;
$this->userId = $userId;
}
public function getEmailAddress(): string
{
return $this->emailAddress;
}
public function getType(): ?string
{
return $this->type;
}
public function getId(): ?string
{
return $this->id;
}
public function getUserId(): ?string
{
return $this->userId;
}
}

View File

@@ -0,0 +1,168 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Email;
use League\HTMLToMarkdown\HtmlConverter;
class Util
{
static public function parseFromName(string $string): string
{
$fromName = '';
if ($string && stripos($string, '<') !== false) {
/** @var string $replacedString */
$replacedString = preg_replace('/(<.*>)/', '', $string);
$fromName = trim($replacedString, '" ');
}
return $fromName;
}
static public function parseFromAddress(string $string): string
{
if (!$string) {
return '';
}
if (stripos($string, '<') !== false) {
$fromAddress = '';
if (preg_match('/<(.*)>/', $string, $matches)) {
$fromAddress = trim($matches[1]);
}
return $fromAddress;
}
return $string;
}
/**
* Strip HTML.
*
* @since 9.1.0
*/
static public function stripHtml(string $string): string
{
if (!$string) {
return '';
}
$converter = new HtmlConverter();
$converter->setOptions([
'remove_nodes' => 'img',
'strip_tags' => true,
]);
$string = $converter->convert($string) ?: '';
$string = (string) preg_replace('~\R~u', "\r\n", $string);
$reList = [
'&(quot|#34);',
'&(amp|#38);',
'&(lt|#60);',
'&(gt|#62);',
'&(nbsp|#160);',
'&(iexcl|#161);',
'&(cent|#162);',
'&(pound|#163);',
'&(copy|#169);',
'&(reg|#174);',
];
$replaceList = [
'',
'&',
'<',
'>',
' ',
'¡',
'¢',
'£',
'©',
'®',
];
foreach ($reList as $i => $re) {
$string = (string) mb_ereg_replace($re, $replaceList[$i], $string, 'i');
}
return $string;
}
/**
* Strip a quote part in a plain text.
*
* @since 9.0.0
*/
static public function stripPlainTextQuotePart(string $string): string
{
if (!$string) {
return '';
}
$lines = preg_split("/\r\n|\n|\r/", $string);
if (!is_array($lines)) {
return '';
}
$endIndex = count($lines) - 1;
for ($i = count($lines) - 1; $i >= 0; $i--) {
$line = $lines[$i];
if (str_starts_with($line, '>') || $line === '') {
$endIndex = $i;
continue;
}
break;
}
$lines = array_slice($lines, 0, $endIndex);
if (count($lines) > 2) {
$lastIndex = count($lines) - 1;
if (str_ends_with($lines[$lastIndex], ':') && $lines[$lastIndex - 1] === '') {
$lines = array_slice($lines, 0, count($lines) - 2);
}
}
return implode("\r\n", $lines);
}
}