Skip to content

Commit

Permalink
Merge pull request #13 from xedi/feat/attach_files
Browse files Browse the repository at this point in the history
Added ability to add attachments to emails
  • Loading branch information
ehtishamSaleem committed Mar 24, 2022
2 parents 133d77e + d91ee7a commit 69d059c
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/Contracts/Mailable.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,22 @@ public function validateSubject();
* @return string API data
*/
public function buildSubject(): array;

/**
* Set Attachment
*
* @param $attachment string attachment file object
* @param $mime_type string attachment mime type
* @param $name string attachment filename
*
* @return mixed
*/
public function setAttachment(string $attachment, string $mime_type, string $name);

/**
* Build Attachment
*
* @return array
*/
public function buildAttachment();
}
57 changes: 57 additions & 0 deletions lib/Mail/Concerns/HasAttachment.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Xedi\SendGrid\Mail\Concerns;

/**
* HasAttachment Concern
*
* @package Xedi\SendGrid\Mail\Concerns
* @author Adam Witeszczak <adam@xedi.com>
*/
trait HasAttachment
{
protected $attachments = [];

/**
* Set Attachment
*
* @param $attachment string attachment file as string
* @param $mime_type string mime type
* @param $name string name
*
* @return $this
*/
public function setAttachment($attachment, $mime_type, $name)
{
$toAttach = new \StdClass();
$toAttach->content = base64_encode($attachment);
$toAttach->type = $mime_type;
$toAttach->filename = $name;
$toAttach->disposition = 'attachment';
$this->attachments[] = $toAttach;

return $this;
}

/**
* Has Attachment
*
* @return bool
*/
public function hasAttachment(): bool
{
return count($this->attachments) > 0;
}

/**
* Build the Attachment data for the API Request
*
* @return string API data
*/
public function buildAttachment(): array
{
return [
'attachments' => $this->attachments
];
}
}
6 changes: 6 additions & 0 deletions lib/Mail/Mail.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Xedi\SendGrid\Mail\Concerns\HasRecipients;
use Xedi\SendGrid\Mail\Concerns\HasSender;
use Xedi\SendGrid\Mail\Concerns\HasSubject;
use Xedi\SendGrid\Mail\Concerns\HasAttachment;

/**
* Class Mail
Expand All @@ -18,6 +19,7 @@
*/
class Mail implements Mailable
{
use HasAttachment;
use HasContent;
use HasRecipients;
use HasSender;
Expand Down Expand Up @@ -55,6 +57,10 @@ public function send(Client $client): Response
$this->buildSubject()
);

if ($this->hasAttachment()) {
$data = array_merge($data, $this->buildAttachment());
}

return $client->post('v3/mail/send', $data);
}
}

0 comments on commit 69d059c

Please sign in to comment.