Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use upload session to upload large files #42

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
83 changes: 76 additions & 7 deletions src/MicrosoftGraphTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Header\HeaderInterface;
use Symfony\Component\Mime\MessageConverter;
use Symfony\Component\Mime\Part\DataPart;

class MicrosoftGraphTransport extends AbstractTransport
{
protected const MAX_INLINE_ATTACHMENT_SIZE = 3.5 * 1024 * 1024;
protected const LARGE_ATTACHMENT_CHUNK_SIZE = 1024 * 1024;

public function __construct(
protected MicrosoftGraphApiService $microsoftGraphApiService,
?EventDispatcherInterface $dispatcher = null,
Expand All @@ -40,7 +44,7 @@ protected function doSend(SentMessage $message): void

$html = $email->getHtmlBody();

[$attachments, $html] = $this->prepareAttachments($email, $html);
[$attachments, $largeAttachments, $html] = $this->prepareAttachments($email, $html);

$payload = [
'message' => [
Expand All @@ -59,38 +63,62 @@ protected function doSend(SentMessage $message): void
'saveToSentItems' => config('mail.mailers.microsoft-graph.save_to_sent_items', false) ?? false,
];

$from = $envelope->getSender()->getAddress();

if (filled($headers = $this->getInternetMessageHeaders($email))) {
$payload['message']['internetMessageHeaders'] = $headers;
}

$this->microsoftGraphApiService->sendMail($envelope->getSender()->getAddress(), $payload);
$skipLargeAttachments = config('mail.mailers.microsoft-graph.skip_large_attachments', false);
if ($skipLargeAttachments || count($largeAttachments) === 0) {
$this->microsoftGraphApiService->sendMail($from, $payload);

return;
}

$graphMessageResponse = $this->microsoftGraphApiService->saveMessage($from, $payload['message']);
$graphMessage = $graphMessageResponse->json();
$graphMessageId = $graphMessage['id'];

$this->prepareLargeAttachments($largeAttachments, $from, $graphMessageId);

$this->microsoftGraphApiService->sendMessage($from, $graphMessageId);
}

/**
* @return array<int, array<int<0, max>, array<string, bool|string|null>>|string|null>
* @return array<int, array<int<0, max>, array<string, bool|string|null>>|string|null, DataPart[]>
*/
protected function prepareAttachments(Email $email, ?string $html): array
{
$attachments = [];
$largeAttachments = [];
foreach ($email->getAttachments() as $attachment) {
$content = $attachment->getBody();
$contentSize = strlen($content);

if ($contentSize > self::MAX_INLINE_ATTACHMENT_SIZE) {
$largeAttachments[] = $attachment;
continue;
}

$headers = $attachment->getPreparedHeaders();
$fileName = $headers->getHeaderParameter('Content-Disposition', 'filename');

$attachments[] = [
'@odata.type' => '#microsoft.graph.fileAttachment',
'name' => $fileName,
'contentType' => $attachment->getMediaType(),
'contentBytes' => base64_encode($attachment->getBody()),
'contentBytes' => base64_encode($content),
'contentId' => $fileName,
'isInline' => $headers->getHeaderBody('Content-Disposition') === 'inline',
];
}

return [$attachments, $html];
return [$attachments, $largeAttachments, $html];
}

/**
* @param Collection<array-key, Address> $recipients
* @param Collection<array-key, Address> $recipients
* @return array<array-key, array<string, array<string, string>>>
*/
protected function transformEmailAddresses(Collection $recipients): array
Expand All @@ -115,7 +143,7 @@ protected function transformEmailAddress(Address $address): array
protected function getRecipients(Email $email, Envelope $envelope): Collection
{
return collect($envelope->getRecipients())
->filter(fn (Address $address) => ! in_array($address, array_merge($email->getCc(), $email->getBcc()), true));
->filter(fn (Address $address) => !in_array($address, array_merge($email->getCc(), $email->getBcc()), true));
}

/**
Expand All @@ -131,4 +159,45 @@ protected function getInternetMessageHeaders(Email $email): ?array
->values()
->all() ?: null;
}

/**
* @param DataPart[] $largeAttachments
* @param string $from
* @param string $graphMessageId
* @return void
*/
private function prepareLargeAttachments(array $largeAttachments, string $from, string $graphMessageId): void
{
foreach ($largeAttachments as $attachment) {
$content = $attachment->getBody();
$contentSize = strlen($content);

$uploadSessionResponse = $this->microsoftGraphApiService->createUploadSession($from, $graphMessageId, [
'AttachmentItem' => [
'attachmentType' => 'file',
'name' => $attachment->getFilename(),
'size' => $contentSize,
]
]);
$uploadSession = $uploadSessionResponse->json();
$uploadUrl = $uploadSession['uploadUrl'];

$this->uploadLargeAttachment($uploadUrl, $content, $contentSize);
}
}

private function uploadLargeAttachment(string $uploadUrl, string $content, int $contentSize): void
{
$totalChunks = ceil($contentSize / self::LARGE_ATTACHMENT_CHUNK_SIZE);
$start = 0;

for ($chunkIndex = 0; $chunkIndex < $totalChunks; $chunkIndex++) {
$end = min($start + self::LARGE_ATTACHMENT_CHUNK_SIZE - 1, $contentSize - 1);
$chunk = substr($content, $start, self::LARGE_ATTACHMENT_CHUNK_SIZE);

$this->microsoftGraphApiService->uploadChunk($uploadUrl, $chunk, $start, $end, $contentSize);

$start = $end + 1;
}
}
}
32 changes: 32 additions & 0 deletions src/Services/MicrosoftGraphApiService.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,38 @@ public function sendMail(string $from, array $payload): Response
->throw();
}

public function saveMessage(string $from, array $payload): Response
{
return $this->getBaseRequest()
->post("/users/{$from}/messages", $payload)
->throw();
}

public function sendMessage(string $from, string $messageId): Response
{
return $this->getBaseRequest()
->post("/users/{$from}/messages/{$messageId}/send")
->throw();
}

public function createUploadSession(string $from, string $messageId, array $payload): Response
{
return $this->getBaseRequest()
->post("/users/{$from}/messages/{$messageId}/attachments/createUploadSession", $payload)
->throw();
}

public function uploadChunk(string $uploadUrl, mixed $chunk, int|string $start, int|string $end, int|string $contentSize): Response
{
return Http::withHeaders([
'Content-Length' => strlen($chunk),
'Content-Range' => "bytes $start-$end/$contentSize",
])
->withBody($chunk, 'application/octet-stream')
->put($uploadUrl)
->throw();
}

protected function getBaseRequest(): PendingRequest
{
return Http::withToken($this->getAccessToken())
Expand Down