Skip to content

Instantly share code, notes, and snippets.

@ruman
Forked from joe-niland/sendgrid php attachments
Created November 11, 2020 15:20
Show Gist options
  • Save ruman/8a7f22a9b64e1c3b9f8678be0f4ca7f6 to your computer and use it in GitHub Desktop.
Save ruman/8a7f22a9b64e1c3b9f8678be0f4ca7f6 to your computer and use it in GitHub Desktop.
<?php
// If you are using Composer
require 'vendor/autoload.php';
use SendGrid\Mail;
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
$email = new SendGrid\Email("Me", "me@example.com");
$mail = new SendGrid\Mail();
$mail->setFrom($email);
$mail->setSubject("Attachment Test");
$p = new \SendGrid\Personalization();
$p->addTo($email);
$c = new \SendGrid\Content("text/plain", "Hi");
$mail->addPersonalization($p);
$mail->addContent($c);
$att1 = new \SendGrid\Attachment();
$att1->setContent( file_get_contents("test_files/1/1.txt") );
$att1->setType("text/plain");
$att1->setFilename("1.txt");
$att1->setDisposition("attachment");
$mail->addAttachment( $att1 );
$att2 = new \SendGrid\Attachment();
$att2->setContent( file_get_contents("test_files/2/1.txt") );
$att2->setType("text/plain");
$att2->setFilename("1.txt");
$att2->setDisposition("attachment");
$mail->addAttachment( $att2 );
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode() . "\n";
echo json_encode( json_decode($response->body()), JSON_PRETTY_PRINT) . "\n";
var_dump($response->headers());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment