Отправка вложенных файлов с помощью PHPMailer в фреймворке Slim php - PullRequest
0 голосов
/ 11 июня 2018

Я понимаю, что PHPmailer - одна из лучших, если не лучшая библиотека php для отправки писем.В последнее время я работал над API с использованием slimphp и пытался отправить электронное письмо с вложенным файлом.Поскольку slimphp не предоставляет php $ _FILES (по крайней мере, не так просто), но использует $ request-> getUploadedFiles (), я хотел знать, как можно отправить электронное письмо с вложенным файлом, используя slimphp и PHPMailer

1 Ответ

0 голосов
/ 11 июня 2018
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

});
...