Search code examples
phpemailemail-attachmentssendgrid

Send file attachment with SendGrid PHP (sendgrid-php library)


When I try to send an attachment using the SendGrid PHP library (https://github.com/sendgrid/sendgrid-php), the function fails (white screen). Removing the "setAttachment" line makes it work again.

Here is my code:

require "sendgrid-php/sendgrid-php.php";
function sendgrid() {

   $recips = array("me@mydomain.ca");
   $categories = array("test");



   $sendgrid = new SendGrid("API key removed");

   $email = new SendGrid\Email();
   $email
   ->setSmtpapiTos($recips)
   ->setFrom('mailroom@mydomain.ca')
   ->setSubject('Testing Sendgrid')
   ->setText('Hello World! Testing...')
   ->setHtml('<strong>Hello World!</strong>')
   ->setCategories($categories)
   ->setAttachment('test.txt')
   ;


   //$sendgrid->send($email);

   $res = $sendgrid->send($email);

   var_dump($res);
}

sendgrid();

As far as I can tell, I'm following the documentation, but I wonder if I haven't formatted the path to the file correctly. "Test.txt" is in the same directory as the file that contains the above code.

Can anyone offer any suggestions?


Solution

  • try this

     ->setAttachment(realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR.'test.txt');