Sendgrid file attachement issue.

January 20, 2020 at 23:16:41
Specs: Windows 10
I tried to send email with attachment using sendgrid, i can able to send the mail successfully,but i cant open the attached file.

find below is my code.
i'm not have much experience in Sendgrid php.

$user = 'sendgridusername'; // place SG username here
$pass = 'sendgrid password'; // place SG password here
$frm_email = $_POST['userEmail'];
$to_Email = ""; //Replace with recipient email address
$from_Email = $_POST['userEmail']; ; //From email address (eg:
$subject = 'Feedback'; //Subject line for emails

//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

//exit script outputting json data
$output = json_encode(
'text' => 'Request must come from Ajax'


//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userProduct"]) || !isset($_POST["userMessage"]))
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));

//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Product = filter_var($_POST["userProduct"], FILTER_SANITIZE_STRING);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

$mail_body .= "\r\nSender Name: ".$user_Name; //sender name
$mail_body .="\r\nSender Email: ".$user_Email; //sender email
$mail_body .="\r\nProduct: ".$user_Product; //sender phone
$mail_body .= "\r\n\r\nFeedback: " .$user_Message;
$mail_body .="\r\n\r\n";

//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
// if(!is_numeric($user_Product)) //check entered data is numbers
// {
// $output = json_encode(array('type'=>'error', 'text' => 'Only numbers allowed in phone field'));
// die($output);
// }
if(strlen($user_Message)<5) //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));

### Attachment Preparation ###
$file_attached = false; //initially file is not attached

if(isset($_FILES['file_attach'])) //check uploaded file
//get file details we need
$file_tmp_name = $_FILES['file_attach']['tmp_name'];
$file_name = $_FILES['file_attach']['name'];
$file_size = $_FILES['file_attach']['size'];
$file_type = $_FILES['file_attach']['type'];
$file_error = $_FILES['file_attach']['error'];
$filePath = dirname(__FILE__);

//exit script and output error if we encounter any
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder" );

$output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));

//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
$encoded_content = chunk_split(base64_encode($content));

//now we know we have the file for attachment, set $file_attached to true
$file_attached = true;

if($file_attached) //continue if we have the file
# Mail headers should work with most clients (including thunderbird)
$headers = "MIME-Version: 1.0\r\n";
$headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
$headers .= "From:".$from_Email."\r\n";
$headers .= "Subject:".$subject."\r\n";
$headers .= "Reply-To: ".$user_Email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";

$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=".md5('boundary2')."\r\n\r\n";

$headers .= "--".md5('boundary2')."\r\n";
$headers .= "Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n";
$headers .= $mail_body."\r\n\r\n";

$headers .= "--".md5('boundary2')."--\r\n";
$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: ".$file_type."; ";
$headers .= "name=\"".$file_name."\"\r\n";
$headers .= "Content-Transfer-Encoding:base64\r\n";
$headers .= "Content-Disposition:attachment; ";
$headers .= "filename=\"".$file_name."\"\r\n";
$headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
$headers .= $encoded_content."\r\n";
$headers .= "--".md5('boundary1')."--";
# Mail headers for plain text mail
$headers = 'From: '.$from_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

//send the mail
//$sentMail = mail($to_Email, $subject, $mail_body, $headers, $user, $pass);

$params = array(
'api_user' => "$user",
'api_key' => "$pass",
'to' => "$to_Email", // set TO address to have the contact form's email content sent to
'subject' => "$subject", // Either give a subject for each submission, or set to $subject
'headers' => "$headers",

'html' => "<html><head><title> Contact Form</title><body>
Name: $user_Name\n

Email: $user_Email\n

Product: $user_Product\n

Message: $user_Message <body></title></head></html>", // Set HTML here. Will still need to make sure to reference post data names
'text' => "
Name: $user_Name\n
Email: $user_Email\n
Subject: $subject\n
'from' => "", // set from address here, it can really be anything
'files['.$file_name.']' => '@'.$encoded_content

$request = '';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
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);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);

if(!$response) //output success or failure messages
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for your Email.'));
// print everything out

See More: Sendgrid file attachement issue.

Reply ↓  Report •
Related Solutions

Ask Question