Hi
After this thread I wrote a custom formula function which allows me to send an email using a specific user:
But now when I call the custom function in a formular, the email gets sent twice:
- One time it gets sent using the correct user and every user-based variable in the email-template get filled in according to the user attributes.
- The other time the email gets sent from the correct user, but the user variables in the email-template get filled in using the System-user attributes.
Has anybody in here an idea, why the email gets sent two times?
After this thread I wrote a custom formula function which allows me to send an email using a specific user:
Code:
<?php
namespace Espo\Custom\Core\Formula\Functions\ExtGroup\EmailGroup;
use Espo\Core\Formula\{
Functions\BaseFunction,
ArgumentList,
};
use Espo\Core\Di;
class SendFromUserType extends BaseFunction implements
Di\EntityManagerAware,
Di\ServiceFactoryAware,
Di\ConfigAware
{
use Di\EntityManagerSetter;
use Di\ServiceFactorySetter;
use Di\ConfigSetter;
public function process(ArgumentList $args)
{
if (count($args) < 2) {
$this->throwTooFewArguments(2);
}
$args = $this->evaluate($args);
$emailId = $args[0];
$userId = $args[1];
if (!$emailId || !is_string($emailId)) {
$this->throwBadArgumentType(1, 'string');
}
if (!$userId || !is_string($userId)) {
$this->throwBadArgumentType(1, 'string');
}
$em = $this->entityManager;
$email = $em->getEntity('Email', $emailId);
$user = $em->getEntity('User', $userId);
if (!$email) {
$this->log("Email '{$emailId}' does not exist.");
return false;
}
if (!$user) {
$this->log("User '{$userId}' does not exist.");
return false;
}
$status = $email->get('status');
if ($status && in_array($status, ['Sent'])) {
$this->log("Can't send email that has 'Sent' status.");
return false;
}
$service = $this->serviceFactory->create('Email');
$service->loadAdditionalFields($email);
$toSave = false;
if ($status !== 'Sending') {
$email->set('status', 'Sending');
$toSave = true;
}
if (!$email->get('from')) {
$from = $this->config->get('outboundEmailFromAddress');
if ($from) {
$email->set('from', $from);
$toSave = true;
}
}
if ($toSave) {
$em->saveEntity($email, [
'modifiedById' => 'system',
'silent' => true,
]);
}
try {
$service->sendEntity($email,$user);
} catch (\Exception $e) {
$message = $e->getMessage();
$this->log("Error while sending. Message: {$message}." , 'error');
return false;
}
return true;
}
}
- One time it gets sent using the correct user and every user-based variable in the email-template get filled in according to the user attributes.
- The other time the email gets sent from the correct user, but the user variables in the email-template get filled in using the System-user attributes.
Has anybody in here an idea, why the email gets sent two times?

Comment