【问题标题】:Sending File Attachment with PHPMailer in Slim php framework在 Slim php 框架中使用 PHPMailer 发送文件附件
【发布时间】:2018-06-13 16:50:32
【问题描述】:

我知道 PHPmailer 是最好的发送电子邮件的 php 库之一。最近我一直在使用 slimphp 开发 API,并试图发送带有文件附件的电子邮件。由于 slimphp 没有公开 php $_FILES (至少没有那么直接)而是使用 $request->getUploadedFiles() ,我想知道如何使用 slimphp 和 PHPMailer 发送带有文件附件的电子邮件

【问题讨论】:

  • 只要上传的文件在你的本地文件系统中是可识别的,你可以将PHPMailer的addAttachment指向它,就是这样。

标签: php phpmailer slim slim-3


【解决方案1】:
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

});

【讨论】:

  • 在getUploadedFiles 的响应中使它们可用之前检查slim 是否验证上传的文件是值得的;这可能意味着后续的tempnam 和move_uploaded_file 调用是不必要的。
猜你喜欢
  • 1970-01-01
  • 2020-11-04
  • 2012-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
相关资源
最近更新 更多