如何用composer安裝phpmailer(含設定教學)

教學目的主要有兩個
- 讓用家掌握使用終端(Terminal)及Composer的流程
-了解SMTP設定

為何需要phpmailer發送電郵?

近年垃圾電郵問題越趨嚴重,相對的主要電郵服務商如Yahoo跟Google一直在提高一些返垃圾電郵(Anti-spam)的要求。這個情況下單純使用php sendmail發送電郵很容易會被錯誤辨識為垃圾郵件,又或者需要複雜的Email Header設定才能達到成功送達效果,而phpmailer就是其中一個簡單的解決方案。

 

1) 首先登入Directadmin網上控制台,進入"系統資訊和檔案" > "終端"

2) 先進入public_html 資料夾(假設php script需要公開),然後輸入安裝指令

composer require phpmailer/phpmailer

3) 安裝完成後,可以參考以下示範
(源始碼來自 https://github.com/PHPMailer/PHPMailer )

4) 特別留意源始碼的登入設定,包括


$mail->Host = 'mail.floppy-demo.com';
如果使用Gmail發送電郵,主機名稱應該是smtp.gmail.com

$mail->Username = '[email protected]';
$mail->Password = 'PASSWORD';
如果使用Gmail發送電郵,電郵密碼應該是App Password,不懂如果取得可參考這個教學。 

$mail->setFrom('[email protected]', '寄件者名稱');
寄件者電郵地址必須跟用家使用的SMTP帳號相關,例如不能SMTP用GMAIL的,但寄件電郵地址用科比的,反之亦然。

<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'mail.floppy-demo.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = '[email protected]';                     //SMTP username
    $mail->Password   = 'PASSWORD';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('[email protected]', '寄件者名稱');
    $mail->addAddress('[email protected]', '收件者名稱');     //Add a recipient


    //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. Mailer Error: {$mail->ErrorInfo}";
}

 

  • 0 Utenti hanno trovato utile questa risposta
Hai trovato utile questa risposta?

Articoli Correlati

如何更改php版本?

現時科比全部主機預設都有提供php5.6/7.4/8.2供用家選擇使用,系統預設php版本是7.4,如需要更改請參考以下教學。 1) 進入"帳號管理" > "域名設定" >...

php Cron 排程設定

1) 在Directadmin 首頁,選擇「Cron任務」 2) 按「建立定時任務」 3) 在「命令」部份,首先需要確認現在網站使用那個php版本,假設是php...