我理解PHPmailer是用于发送电子邮件的最佳PHP库之一。最近我一直在使用slimphp处理API,并试图发送带有文件附件的电子邮件。由于slimphp没有暴露php $ _FILES(至少没有那么直接)但使用$ request-> getUploadedFiles(),我想知道如何使用slimphp和PHPMailer发送带有文件附件的电子邮件
答案 0 :(得分:2)
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 = 'admin@yourdomain.com';
$mail->Password = 'your password here';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('admin@yourdomain.com', '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
});