如何修改SendGrid代码实现表单附件邮件发送?
Adding File Attachments to SendGrid Web API Call from a Form
Let's fix your code to handle file uploads from your form and send them as attachments via SendGrid. First, make sure your HTML form has the enctype="multipart/form-data" attribute—this is mandatory for file uploads to work properly.
Step-by-Step Code Modifications
Here's the updated version of your code with full attachment support:
// Grab the uploaded file from your form (adjust 'attachment' to match your file input's name attribute) $uploadedFile = $_FILES['attachment']; // Basic validation: Check if the file uploaded without errors if ($uploadedFile['error'] !== UPLOAD_ERR_OK) { die("File upload failed with error code: " . $uploadedFile['error']); } // Read the file content and encode it to base64 (required format for SendGrid attachments) $fileContent = file_get_contents($uploadedFile['tmp_name']); $base64Content = base64_encode($fileContent); // Build your SendGrid parameters, adding the attachment details $params = array( 'api_user' => $user, 'api_key' => $pass, 'to' => 'the recipient email', 'subject' => 'New Careers', 'html' => $email, 'text' => $email, 'from' => 'the sender email', // Add attachment metadata and content 'attachments[0][filename]' => $uploadedFile['name'], 'attachments[0][content]' => $base64Content, 'attachments[0][type]' => $uploadedFile['type'], 'attachments[0][disposition]' => 'attachment' ); $request = $url . 'api/mail.send.json'; $session = curl_init($request); // Curl will automatically handle multipart/form-data when passing an array to CURLOPT_POSTFIELDS curl_setopt($session, CURLOPT_POST, true); curl_setopt($session, CURLOPT_POSTFIELDS, $params); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($session); curl_close($session); // Optional: Debug the response to check for SendGrid errors var_dump(json_decode($response));
Key Details to Remember:
- Form Requirement: Your HTML form must include
<form ... enctype="multipart/form-data">—without this, the$_FILESsuperglobal won't receive the uploaded file. - File Input Name: Replace
'attachment'in$_FILES['attachment']with the actualnamevalue of your form's file input (e.g., if your input is<input type="file" name="resume">, use$_FILES['resume']). - Multiple Attachments: To support multiple files, loop through the
$_FILESarray and add additional entries likeattachments[1][filename],attachments[1][content], etc., for each file. - Extra Validation: The example includes basic error checking—you’ll likely want to add more rules (like file size limits or allowed file types) based on your use case.
内容的提问来源于stack exchange,提问作者EnexoOnoma
相关产品推荐
相关产品推荐

