Skip to content

Commit 2c72004

Browse files
authored
Adds the ability to attach files (#9)
1 parent 91b13ac commit 2c72004

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/SendGridMessage.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use SendGrid\Mail\From;
77
use SendGrid\Mail\Mail;
88
use SendGrid\Mail\ReplyTo;
9+
use SendGrid\Mail\Attachment;
910

1011
class SendGridMessage
1112
{
@@ -42,6 +43,13 @@ class SendGridMessage
4243
*/
4344
public $payload = [];
4445

46+
/**
47+
* An array of attachments for the message.
48+
*
49+
* @var array
50+
*/
51+
public $attachments = [];
52+
4553
/**
4654
* The sandbox mode for SendGrid
4755
*
@@ -103,6 +111,26 @@ public function payload($payload)
103111
return $this;
104112
}
105113

114+
public function attach($attachments)
115+
{
116+
/*
117+
$attachments should be an array of individual attachments. content should be base64 encoded.
118+
119+
Example:
120+
$attachments = array(
121+
array(
122+
'content' => base64_encode($content),
123+
'type' => 'application/pdf',
124+
'filename' => 'filename.pdf'
125+
)
126+
);
127+
*/
128+
129+
$this->attachments = $attachments;
130+
131+
return $this;
132+
}
133+
106134
/**
107135
* @return Mail
108136
*/
@@ -124,6 +152,24 @@ public function build(): Mail
124152
$email->addDynamicTemplateData((string) $key, $value);
125153
}
126154

155+
if (is_array($this->attachments) && !empty($this->attachments)) {
156+
foreach ($this->attachments as $attachment) {
157+
$disposition = (isset($attachment['disposition'])) ? strtolower($attachment['disposition']) : "attachment";
158+
159+
$sgAttachment = new Attachment();
160+
$sgAttachment->setType($attachment['type']);
161+
$sgAttachment->setContent($attachment['content']);
162+
$sgAttachment->setDisposition($disposition);
163+
$sgAttachment->setFilename($attachment['filename']);
164+
165+
if ($disposition === "inline") {
166+
$sgAttachment->setContentID($attachment['filename']);
167+
}
168+
169+
$email->addAttachment($sgAttachment);
170+
}
171+
}
172+
127173
return $email;
128174
}
129175

0 commit comments

Comments
 (0)