1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-11 05:32:39 +01:00
invoiceninja/app/Helpers/Mail/Office365MailTransport.php

304 lines
11 KiB
PHP
Raw Normal View History

2022-06-17 07:42:14 +02:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Helpers\Mail;
2022-06-17 10:28:31 +02:00
use Illuminate\Support\Str;
2022-06-17 07:42:14 +02:00
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model\UploadSession;
use Swift_Mime_SimpleMessage;
2022-07-11 04:48:59 +02:00
use Symfony\Component\Mailer\Transport\AbstractTransport;
2022-06-17 07:42:14 +02:00
2022-07-11 04:48:59 +02:00
class Office365MailTransport extends AbstractTransport
2022-06-17 07:42:14 +02:00
{
public function __construct()
{
}
2022-07-11 04:48:59 +02:00
public function doSend(SentMessage $message, &$failedRecipients = null)
2022-06-17 07:42:14 +02:00
{
2022-07-11 04:48:59 +02:00
$message = MessageConverter::toEmail($message->getOriginalMessage());
2022-06-17 07:42:14 +02:00
$this->beforeSendPerformed($message);
$graph = new Graph();
2022-06-17 10:28:31 +02:00
$token = $message->getHeaders()->get('GmailToken')->getValue();
2022-06-17 07:42:14 +02:00
2022-06-17 10:28:31 +02:00
$graph->setAccessToken($token);
2022-06-17 07:42:14 +02:00
// Special treatment if the message has too large attachments
$messageBody = $this->getBody($message, true);
$messageBodySizeMb = json_encode($messageBody);
$messageBodySizeMb = strlen($messageBodySizeMb);
$messageBodySizeMb = $messageBodySizeMb / 1048576; //byte -> mb
if ($messageBodySizeMb >= 4) {
unset($messageBody);
$graphMessage = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages')
2022-06-17 07:42:14 +02:00
->attachBody($this->getBody($message))
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
foreach ($message->getChildren() as $attachment) {
if ($attachment instanceof \Swift_Mime_SimpleMimeEntity) {
$fileName = $attachment->getHeaders()->get('Content-Type')->getParameter('name');
$content = $attachment->getBody();
$fileSize = strlen($content);
$size = $fileSize / 1048576; //byte -> mb
$id = $attachment->getId();
$attachmentMessage = [
'AttachmentItem' => [
'attachmentType' => 'file',
'name' => $fileName,
'size' => strlen($content),
],
2022-06-17 07:42:14 +02:00
];
if ($size <= 3) { //ErrorAttachmentSizeShouldNotBeLessThanMinimumSize if attachment <= 3mb, then we need to add this
$attachmentBody = [
'@odata.type' => '#microsoft.graph.fileAttachment',
'name' => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
'contentType' => $attachment->getBodyContentType(),
'contentBytes' => base64_encode($attachment->getBody()),
'contentId' => $id,
2022-06-17 07:42:14 +02:00
];
$addAttachment = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages/'.$graphMessage->getId().'/attachments')
2022-06-17 07:42:14 +02:00
->attachBody($attachmentBody)
->setReturnType(UploadSession::class)
->execute();
} else {
//upload the files in chunks of 4mb....
$uploadSession = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages/'.$graphMessage->getId().'/attachments/createUploadSession')
2022-06-17 07:42:14 +02:00
->attachBody($attachmentMessage)
->setReturnType(UploadSession::class)
->execute();
$fragSize = 1024 * 1024 * 4; //4mb at once...
2022-06-17 07:42:14 +02:00
$numFragments = ceil($fileSize / $fragSize);
$contentChunked = str_split($content, $fragSize);
$bytesRemaining = $fileSize;
$i = 0;
while ($i < $numFragments) {
$chunkSize = $numBytes = $fragSize;
$start = $i * $fragSize;
$end = $i * $fragSize + $chunkSize - 1;
if ($bytesRemaining < $chunkSize) {
$chunkSize = $numBytes = $bytesRemaining;
$end = $fileSize - 1;
}
$data = $contentChunked[$i];
$content_range = 'bytes '.$start.'-'.$end.'/'.$fileSize;
2022-06-17 07:42:14 +02:00
$headers = [
'Content-Length' => $numBytes,
'Content-Range' => $content_range,
2022-06-17 07:42:14 +02:00
];
$client = new \GuzzleHttp\Client();
$tmp = $client->put($uploadSession->getUploadUrl(), [
'headers' => $headers,
'body' => $data,
'allow_redirects' => false,
'timeout' => 1000,
2022-06-17 07:42:14 +02:00
]);
$result = $tmp->getBody().'';
2022-06-17 07:42:14 +02:00
$result = json_decode($result); //if body == empty, then the file was successfully uploaded
$bytesRemaining = $bytesRemaining - $chunkSize;
$i++;
}
}
}
}
//definetly send the message
$graph->createRequest('POST', '/users/'.key($message->getFrom()).'/messages/'.$graphMessage->getId().'/send')->execute();
2022-06-17 07:42:14 +02:00
} else {
2022-06-17 12:13:16 +02:00
try {
$graphMessage = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/sendmail')
2022-06-17 12:13:16 +02:00
->attachBody($messageBody)
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
} catch (\Exception $e) {
2022-06-17 12:13:16 +02:00
sleep(5);
$graphMessage = $graph->createRequest('POST', '/users/'.key($message->getFrom()).'/sendmail')
2022-06-17 12:13:16 +02:00
->attachBody($messageBody)
->setReturnType(\Microsoft\Graph\Model\Message::class)
->execute();
}
2022-06-17 07:42:14 +02:00
}
$this->sendPerformed($message);
return $this->numberOfRecipients($message);
}
/**
* Get body for the message.
*
* @param \Swift_Mime_SimpleMessage $message
* @param bool $withAttachments
* @return array
*/
protected function getBody(Swift_Mime_SimpleMessage $message, $withAttachments = false)
{
$messageData = [
'from' => [
'emailAddress' => [
'address' => key($message->getFrom()),
'name' => current($message->getFrom()),
],
2022-06-17 07:42:14 +02:00
],
'toRecipients' => $this->getTo($message),
'ccRecipients' => $this->getCc($message),
'bccRecipients' => $this->getBcc($message),
'replyTo' => $this->getReplyTo($message),
'subject' => $message->getSubject(),
'body' => [
'contentType' => $message->getBodyContentType() == 'text/html' ? 'html' : 'text',
'content' => $message->getBody(),
],
2022-06-17 07:42:14 +02:00
];
if ($withAttachments) {
$messageData = ['message' => $messageData];
//add attachments if any
$attachments = [];
foreach ($message->getChildren() as $attachment) {
2022-06-17 10:28:31 +02:00
if ($attachment instanceof \Swift_Mime_SimpleMimeEntity && $attachment->getContentType() != 'text/plain') {
2022-06-17 07:42:14 +02:00
$attachments[] = [
'@odata.type' => '#microsoft.graph.fileAttachment',
'name' => $attachment->getHeaders()->get('Content-Type')->getParameter('name'),
'contentType' => $attachment->getBodyContentType(),
'contentBytes' => base64_encode($attachment->getBody()),
'contentId' => $attachment->getId(),
2022-06-17 07:42:14 +02:00
];
}
}
if (count($attachments) > 0) {
$messageData['message']['attachments'] = $attachments;
}
}
return $messageData;
}
/**
* Get the "to" payload field for the API request.
*
* @param \Swift_Mime_SimpleMessage $message
* @return string
*/
protected function getTo(Swift_Mime_SimpleMessage $message)
{
return collect((array) $message->getTo())->map(function ($display, $address) {
return $display ? [
'emailAddress' => [
'address' => $address,
'name' => $display,
],
2022-06-17 07:42:14 +02:00
] : [
'emailAddress' => [
'address' => $address,
],
2022-06-17 07:42:14 +02:00
];
})->values()->toArray();
}
/**
* Get the "Cc" payload field for the API request.
*
* @param \Swift_Mime_SimpleMessage $message
* @return string
*/
protected function getCc(Swift_Mime_SimpleMessage $message)
{
return collect((array) $message->getCc())->map(function ($display, $address) {
return $display ? [
'emailAddress' => [
'address' => $address,
'name' => $display,
],
2022-06-17 07:42:14 +02:00
] : [
'emailAddress' => [
'address' => $address,
],
2022-06-17 07:42:14 +02:00
];
})->values()->toArray();
}
/**
* Get the "replyTo" payload field for the API request.
*
* @param \Swift_Mime_SimpleMessage $message
* @return string
*/
protected function getReplyTo(Swift_Mime_SimpleMessage $message)
{
return collect((array) $message->getReplyTo())->map(function ($display, $address) {
return $display ? [
'emailAddress' => [
'address' => $address,
'name' => $display,
],
2022-06-17 07:42:14 +02:00
] : [
'emailAddress' => [
'address' => $address,
],
2022-06-17 07:42:14 +02:00
];
})->values()->toArray();
}
/**
* Get the "Bcc" payload field for the API request.
*
* @param \Swift_Mime_SimpleMessage $message
* @return string
*/
protected function getBcc(Swift_Mime_SimpleMessage $message)
{
return collect((array) $message->getBcc())->map(function ($display, $address) {
return $display ? [
'emailAddress' => [
'address' => $address,
'name' => $display,
],
2022-06-17 07:42:14 +02:00
] : [
'emailAddress' => [
'address' => $address,
],
2022-06-17 07:42:14 +02:00
];
})->values()->toArray();
}
/**
* Get all of the contacts for the message.
*
* @param \Swift_Mime_SimpleMessage $message
* @return array
*/
protected function allContacts(Swift_Mime_SimpleMessage $message)
{
return array_merge(
(array) $message->getTo(),
(array) $message->getCc(),
(array) $message->getBcc(),
(array) $message->getReplyTo()
);
}
2022-07-11 04:48:59 +02:00
public function __toString(): string
{
return 'office365';
}
}