2017-12-27 1230 views
0

我以前沒有使用MVC發送過電子郵件,並且有點卡住了。如何通過控制器與MVC發送電子郵件

在我的應用程序文件夾中,我有一個具有Controller.php這樣,core.php中,database.php中一個庫文件夾,我創建Email.php

在Email.php我有一個類:

use PHPMailer\PHPMailer\PHPMailer; 
use PHPMailer\PHPMailer\Exception; 

require '../vendor/autoload.php'; 

class Email { 

    public function sendMail() 
    { 


     $mail = new PHPMailer(true);        // Passing `true` enables exceptions 
     try { 
      //Server settings 
      $mail->SMTPDebug = 2;         // Enable verbose debug output 
      $mail->isSMTP();          // Set mailer to use SMTP 
      $mail->Host = 'mail.example.com'; // Specify main and backup SMTP servers 
      $mail->SMTPAuth = true;        // Enable SMTP authentication 
      $mail->Username = '[email protected]';     // SMTP username 
      $mail->Password = 'secret';       // SMTP password 
      $mail->SMTPSecure = 'tls';       // Enable TLS encryption, `ssl` also accepted 
      $mail->Port = 587;         // TCP port to connect to 

      //Recipients 
      $mail->setFrom('[email protected]'); 
      $mail->addAddress('[email protected]');  // Add a recipient    // Name is optional 
      $mail->addReplyTo('[email protected]'); 


      //Content 
      $mail->isHTML(true);         // Set email format to HTML 
      $mail->Subject = 'Here is the subject'; 
      $mail->Body = 'This is the HTML message body <b>in bold!</b>'; 
      $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; 

      $mail->send(); 
      echo 'Message has been sent'; 
     } catch (Exception $e) { 
      echo 'Message could not be sent.'; 
      echo 'Mailer Error: ' . $mail->ErrorInfo; 
     } 
    } 
} 

我現在試圖在訪問電子郵件視圖時觸發發送電子郵件。但是,我不知道要在控制器中放置什麼。下面的代碼給我一個錯誤。

public function email() 
{ 

    $this->sendMail(); 
    $this->view('pages/email'); 
} 

致命錯誤:未捕獲的錯誤:調用未定義的方法頁面:: Sendmail的()

回答

2

你必須創建類電子郵件的一個實例:

$email = new Email(); 
$email->sendMail(); 
+1

嗯,是的,當然。我多麼愚蠢! – user8463989