I understand PHPmailer is one of the best if not the best php libraries for sending emails. Of late I have been working on an API using slimphp and was trying to send an email with a file attachment. Since slimphp doesn't expose the php $_FILES (at-least no that straight forward) but uses $request->getUploadedFiles() , I wanted to know how you can send an email with a file attachment using slimphp and PHPMailer
use Psr\Http\Message\UploadedFileInterface; //slimphp File upload interface
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->post('/send_mail_Attachment', function ($request, $response){
//get the file from user input
$files = $request->getUploadedFiles();
$uploadedFile = $files['fileName']; //fileName is the file input name
$filename = $uploadedFile->getClientFilename();
$filesize = $image->getSize();
//check file upload error
if ($uploadedFile->getError() != UPLOAD_ERR_OK) {
//return your file upload error here
}
//Check file size
if ($filesize > 557671) {
//return error here if file is larger than 557671
}
//check uploaded file using hash
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $filename));
//upload file to temp location and send
if (move_uploaded_file($uploadedFile->file, $uploadfile)){
//send email with php mailer
$mail = new PHPMailer(true);
try{
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.zoho.com'; //change to gmail
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your password here';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('[email protected]', 'Web Admin');
$mail->addAddress('email address your sending to');
$mail->isHTML(true); //send email in html formart
$mail->Subject = 'email subject here';
$mail->Body = '<h1>Email body here</h1>';
$mail->addAttachment($uploadfile, $fileName); //attach file here
$mail->send();
//return Email sent
}
catch (Exception $e) {
$error = $mail->ErrorInfo;
//return error here
}
}
//return error uploading file
});