Send attachment email with php and sendgrid
I want to send an email with Sendgrid, using cURL. This is a tool I have been using for quite some time now, and everything works perfectly fine when I want to send a simple email.
However now, I'm trying to send an attachment file along with the email. What happens is that I see the file in the email, but it's displayed with only 1KB size and it's impossible to download the file.
I was thinking that this may be a path problem. The paths I tried (assuming the Php file is at the address
mywebsite.com/file.php) are the following :
- 'http://www.mywebsite.com/documents' (an URL)
I also tried to enter the URL to the platform directly into the file path parameter.
The response I obtain from Sendgrid API is
I'm following this guide, here is the code:
$html = '<p>Hello StackOverflow</p>'; $fileName = 'myDocument.pdf'; $filePath = 'http://mywebsite.com/documents' $url = 'https://api.sendgrid.com/'; $user = [MY_USER]; $pass = [MY_PASS]; $js = array( 'sub' => array(':name' => array([MY_FIRSTNAME])), ); $params = array( 'api_user' => $user, 'api_key' => $pass, 'to' => $to, 'subject' => $subject, 'html' => $html, 'from' => $from, 'fromname' => [MY_FROMNAME], 'x-smtpapi' => json_encode($js), 'files['.$fileName.']' => '@'.$filePath.'/'.$fileName ); print_r($params); // AT THAT POINT, WHAT IS PRINTED IS EXACTLY WHAT I EXPECT $request = $url.'api/mail.send.json'; // Generate curl request $session = curl_init($request); // Tell curl to use HTTP POST curl_setopt ($session, CURLOPT_POST, true); // Tell curl that this is the body of the POST curl_setopt ($session, CURLOPT_POSTFIELDS, $params); // Tell curl not to return headers, but do return the response curl_setopt($session, CURLOPT_HEADER, false); // Tell PHP not to use SSLv3 (instead opting for TLS) curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // obtain response $response = curl_exec($session); curl_close($session);
I found a solution, which may not be optimal but which works at least.
'files['.$fileName.']' => '@'.$filePath.'/'.$fileName
I'm a bit surprised that reproducing the documentation of Sendgrid API doesn't work, but maybe there is a cleaner solution which works with it. If so, feel free to share (instead of downvoting my post for example).