2017-12-27 1286 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