--
參考資源
- Send Email using PHPMailer in CodeIgniter - CodexWorld
- GitHub - arquizade/ci-phpmailer: How to integrate PHPMailer with Codeigniter 3
為什麼不繼續使用 CI 內建 mail 功能?因為沒有除錯功能,所以改用 PHPMailer
--
Phpmailer_lib.php
將檔案放到網站上
libraries/Phpmailer_lib.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; class PHPMailer_Lib { public function __construct(){ log_message('Debug', 'PHPMailer class is loaded.'); } public function load(){ // Include PHPMailer library files require_once APPPATH.'third_party/PHPMailer/Exception.php'; require_once APPPATH.'third_party/PHPMailer/PHPMailer.php'; require_once APPPATH.'third_party/PHPMailer/SMTP.php'; $mail = new PHPMailer; return $mail; } } |
--
發信
測試的時候最好設定 Timeout 以及開啟 SMTPDebug
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Mail extends CI_Controller{ function __construct(){ parent::__construct(); } function index(){ // Load PHPMailer library $this->load->library('phpmailer_lib'); // PHPMailer object $mail = $this->phpmailer_lib->load(); // SMTP configuration $mail->isSMTP(); $mail->SMTPDebug = 1; $mail->Timeout = 5; $mail->Host = 'smtp.googlemail.com'; $mail->SMTPAuth = true; $mail->Username = 'xxxx@gmail.com'; $mail->Password = '**********'; $mail->SMTPSecure = 'ssl'; $mail->Port = 465; $mail->setFrom('xxxx@gmail.com', 'xxxxx'); // Add a recipient $mail->addAddress('yyyy@gmail.com'); // Email subject $mail->Subject = 'Send Email via SMTP using PHPMailer in CodeIgniter'; // Set email format to HTML $mail->isHTML(true); // Email body content $mailContent = "<h1>Send HTML Email using SMTP in CodeIgniter</h1> <p>This is a test email sending using SMTP mail server with PHPMailer.</p>"; $mail->Body = $mailContent; // Send email if(!$mail->send()){ echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; }else{ echo 'Message has been sent'; } } } |
--
Username and Password not accepted.
如果確定帳號、密碼都沒錯,那就要到帳號 → 設定 → 安全性,將低安全性應用程式存取權允許
--
691 total views, 1 views today