Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions ProcessMaker/Mail/MicrosoftGraphMessageConverter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

namespace ProcessMaker\Mail;

use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;

class MicrosoftGraphMessageConverter
{
public static function toSendMailPayload(Email $email): array
{
$htmlBody = $email->getHtmlBody();
$textBody = $email->getTextBody();

$message = [
'subject' => $email->getSubject() ?? '',
'body' => [
'contentType' => $htmlBody !== null ? 'HTML' : 'Text',
'content' => $htmlBody ?? $textBody ?? '',
],
'toRecipients' => self::convertAddresses($email->getTo()),
];

$ccRecipients = self::convertAddresses($email->getCc());
if ($ccRecipients) {
$message['ccRecipients'] = $ccRecipients;
}

$bccRecipients = self::convertAddresses($email->getBcc());
if ($bccRecipients) {
$message['bccRecipients'] = $bccRecipients;
}

$attachments = self::convertAttachments($email);
if ($attachments) {
$message['attachments'] = $attachments;
}

return [
'message' => $message,
'saveToSentItems' => true,
];
}

/**
* @param Address[] $addresses
*/
private static function convertAddresses(array $addresses): array
{
return array_map(function (Address $address) {
$emailAddress = ['address' => $address->getAddress()];

if ($address->getName()) {
$emailAddress['name'] = $address->getName();
}

return ['emailAddress' => $emailAddress];
}, $addresses);
}

private static function convertAttachments(Email $email): array
{
$attachments = [];

foreach ($email->getAttachments() as $attachment) {
$attachments[] = [
'@odata.type' => '#microsoft.graph.fileAttachment',
'name' => $attachment->getFilename() ?: 'attachment',
'contentType' => $attachment->getMediaType() . '/' . $attachment->getMediaSubtype(),
'contentBytes' => base64_encode($attachment->getBody()),
];
}

return $attachments;
}
}
57 changes: 57 additions & 0 deletions ProcessMaker/Mail/MicrosoftGraphTokenProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace ProcessMaker\Mail;

use GuzzleHttp\Client;
use RuntimeException;

class MicrosoftGraphTokenProvider
{
private const TOKEN_URL = 'https://login.microsoftonline.com/%s/oauth2/v2.0/token';

private const DEFAULT_SCOPE = 'https://graph.microsoft.com/.default';

public function __construct(
private array $config,
private int|string $serverIndex = 0,
private ?Client $httpClient = null,
) {
}

public function getAccessToken(): string
{
return $this->requestAccessToken();
}

private function requestAccessToken(): string
{
$tenantId = $this->config['tenant_id'] ?? null;
$clientId = $this->config['key'] ?? null;
$clientSecret = $this->config['secret'] ?? null;

if (!$tenantId || !$clientId || !$clientSecret) {
throw new RuntimeException('Microsoft Graph credentials are not configured.');
}

$client = $this->httpClient ?? new Client();
$response = $client->post(sprintf(self::TOKEN_URL, $tenantId), [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'scope' => self::DEFAULT_SCOPE,
'grant_type' => 'client_credentials',
],
'http_errors' => false,
]);

$body = json_decode($response->getBody()->getContents(), true);

if ($response->getStatusCode() >= 400) {
$message = $body['error_description'] ?? $body['error']['message'] ?? 'Unknown error';

throw new RuntimeException('Failed to get Microsoft Graph access token: ' . $message);
}

return $body['access_token'];
}
}
53 changes: 53 additions & 0 deletions ProcessMaker/Mail/Transports/MicrosoftGraphTransport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace ProcessMaker\Mail\Transports;

use GuzzleHttp\Client;
use ProcessMaker\Mail\MicrosoftGraphMessageConverter;
use ProcessMaker\Mail\MicrosoftGraphTokenProvider;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\MessageConverter;

class MicrosoftGraphTransport extends AbstractTransport
{
public function __construct(
private MicrosoftGraphTokenProvider $tokenProvider,
private string $senderEmail,
private ?Client $client = null
) {
parent::__construct();

$this->client = $client ?? new Client([
'base_uri' => 'https://graph.microsoft.com/v1.0/',
]);
}

protected function doSend(SentMessage $message): void
{
$email = MessageConverter::toEmail($message->getOriginalMessage());
$payload = MicrosoftGraphMessageConverter::toSendMailPayload($email);
$token = $this->tokenProvider->getAccessToken();

$response = $this->client->post('users/' . rawurlencode($this->senderEmail) . '/sendMail', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
'http_errors' => false,
]);

if ($response->getStatusCode() >= 400) {
throw new TransportException(
'Microsoft Graph send failed: ' . $response->getBody()->getContents()
);
}
}

public function __toString(): string
{
return 'microsoft-graph';
}
}
22 changes: 22 additions & 0 deletions ProcessMaker/Managers/OauthMailManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use Google\Client as GoogleClient;
use GuzzleHttp\Client;
use Illuminate\Mail\MailManager;
use ProcessMaker\Mail\MicrosoftGraphTokenProvider;
use ProcessMaker\Mail\Transports\MicrosoftGraphTransport;
use ProcessMaker\Models\EnvironmentVariable;
use ProcessMaker\Models\Setting;
use ProcessMaker\Packages\Connectors\Email\EmailConfig;
Expand Down Expand Up @@ -77,6 +79,26 @@ protected function createSmtpTransport($config)
return $transport;
}

public function createTransport(array $config)
{
if ($this->app->config->get('mail.driver') === 'microsoft_graph') {
return $this->createMicrosoftGraphTransport($config);
}

return parent::createTransport($config);
}

protected function createMicrosoftGraphTransport(array $config)
{
return new MicrosoftGraphTransport(
new MicrosoftGraphTokenProvider(
$this->app->config->get('services.microsoft_graph', []),
$this->emailServerIndex ?? 0
),
$this->fromAddress
);
}

public function checkForExpiredAccessToken()
{
switch ($this->authMethod) {
Expand Down
4 changes: 4 additions & 0 deletions config/mail.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@
'transport' => 'array',
],

'microsoft_graph' => [
'transport' => 'microsoft_graph',
],

'failover' => [
'transport' => 'failover',
'mailers' => [
Expand Down
2 changes: 1 addition & 1 deletion resources/js/admin/settings/components/SettingsListing.vue
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ export default {
filterEmailServerButtons(groupName, groupData, btn) {
const authMethod = groupData.find(data => data.key.includes("EMAIL_CONNECTOR_MAIL_AUTH_METHOD"));
const selectedAuthMethod = authMethod ? authMethod.ui.options[authMethod.config] : null;
const showAuthAccBtn = selectedAuthMethod && selectedAuthMethod !== 'standard' ? true : false;
const showAuthAccBtn = selectedAuthMethod && selectedAuthMethod !== 'standard';

if (groupName.includes('Email Server') && !showAuthAccBtn) {
// Returns all 'top' position buttons except the '+ Mail Server' and 'Authorize Account' button for email server tabs
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Tests\Unit\ProcessMaker\Mail;

use ProcessMaker\Mail\MicrosoftGraphMessageConverter;
use Symfony\Component\Mime\Email;
use Tests\TestCase;

class MicrosoftGraphMessageConverterTest extends TestCase
{
public function testToSendMailPayloadIncludesFileAttachments()
{
$email = (new Email())
->to('recipient@example.com')
->subject('With attachment')
->html('<p>Hello</p>')
->attach('file-contents', 'report.txt', 'text/plain');

$payload = MicrosoftGraphMessageConverter::toSendMailPayload($email);

$this->assertSame('With attachment', $payload['message']['subject']);
$this->assertSame('HTML', $payload['message']['body']['contentType']);
$this->assertCount(1, $payload['message']['attachments']);
$this->assertSame([
'@odata.type' => '#microsoft.graph.fileAttachment',
'name' => 'report.txt',
'contentType' => 'text/plain',
'contentBytes' => base64_encode('file-contents'),
], $payload['message']['attachments'][0]);
}

public function testToSendMailPayloadOmitsAttachmentsKeyWhenNonePresent()
{
$email = (new Email())
->to('recipient@example.com')
->subject('No attachment')
->text('Hello');

$payload = MicrosoftGraphMessageConverter::toSendMailPayload($email);

$this->assertArrayNotHasKey('attachments', $payload['message']);
}
}
61 changes: 61 additions & 0 deletions tests/unit/ProcessMaker/Mail/MicrosoftGraphTokenProviderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace Tests\Unit\ProcessMaker\Mail;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Mockery;
use ProcessMaker\Mail\MicrosoftGraphTokenProvider;
use RuntimeException;
use Tests\TestCase;

class MicrosoftGraphTokenProviderTest extends TestCase
{
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}

public function testGetAccessTokenThrowsWhenCredentialsAreMissing()
{
$provider = new MicrosoftGraphTokenProvider([
'tenant_id' => '',
'key' => 'client-id',
'secret' => 'client-secret',
]);

$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Microsoft Graph credentials are not configured.');

$provider->getAccessToken();
}

public function testGetAccessTokenRequestsTokenFromMicrosoft()
{
$tokenResponse = new Response(200, [], json_encode(['access_token' => 'token-from-azure']));

$guzzle = Mockery::mock(Client::class);
$guzzle->shouldReceive('post')
->once()
->with(
'https://login.microsoftonline.com/tenant-id-123/oauth2/v2.0/token',
Mockery::on(function ($options) {
return $options['form_params']['client_id'] === 'client-id-123'
&& $options['form_params']['client_secret'] === 'client-secret-123'
&& $options['form_params']['scope'] === 'https://graph.microsoft.com/.default'
&& $options['form_params']['grant_type'] === 'client_credentials'
&& $options['http_errors'] === false;
})
)
->andReturn($tokenResponse);

$provider = new MicrosoftGraphTokenProvider([
'tenant_id' => 'tenant-id-123',
'key' => 'client-id-123',
'secret' => 'client-secret-123',
], 1, $guzzle);

$this->assertSame('token-from-azure', $provider->getAccessToken());
}
}
Loading