以下僅提供mail()寄信程式撰寫範例,不另提供smtp發信主機,請將程式碼儲存成php檔案,例如:email.php

1.到網路上搜尋並下載phpmailer(或使用以下範例),將檔案解開後放置在 www/ 目錄下

2.將提供的mail.php 放置在 www/ 需要使用的目錄路徑下。

3.系統預設使用25 port發信。 若需要使用SSL發信,請將檔案內的程式碼 $mail->SMTPSecure = 'ssl'; 的註解取消, 並修改 $mail->Port = :25; 改成 465 或587 port

phpmail範例程式碼:

 <?php


use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;


require '/raid/vhost/your.domain/www/phpmailer/src/Exception.php';

require '/raid/vhost/your.domain/www/phpmailer/src/PHPMailer.php';

require '/raid/vhost/your.domain/www/phpmailer/src/SMTP.php';



$mail = new PHPMailer();                               // Passing `true` enables exceptions

try {

    $mail->SMTPDebug = 0;                              // Enable verbose debug output

    $mail->isSMTP();                                   // Set mailer to use SMTP

    $mail->Host = 'your mailserver ip';                // Specify main and backup SMTP servers

    $mail->SMTPAuth = true;                            // Enable SMTP authentication

    $mail->Username = 'from@your.domain';              // SMTP username

    $mail->Password = 'xxxxxxxx';                      // SMTP password

#    $mail->SMTPSecure = 'ssl';                        // Enable TLS encryption, `ssl` also accepted

    $mail->Port = 25;                                  // TCP port to connect to


    $mail->setFrom('from@your.domain', 'from');            // Set mail from

    $mail->addAddress('mailto@mailto.domain', 'mailto');



    $mail->isHTML(true);                               // Set email format to HTML

    $mail->Subject = 'Here is the subject';

    $mail->Body = 'This is the HTML message body in bold!';


    $mail->send();

    echo 'Message has been sent';

} catch (Exception $e) {

    echo 'Message could not be sent.';

    echo 'Mailer Error: ' . $mail->ErrorInfo;

}

?>

使用gmail帳號發信的phpmail程式碼範例:


<?php

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;


require '/raid/vhost/your.domain/www/phpmailer/src/Exception.php';

require '/raid/vhost/your.domain/www/phpmailer/src/PHPMailer.php';

require '/raid/vhost/your.domain/www/phpmailer/src/SMTP.php';


$mail = new PHPMailer;


$mail->isSMTP();


$mail->SMTPDebug = 0;


$mail->Host = 'smtp.gmail.com';


$mail->Port = 465;  //SSL

#$mail->Port = 587;  //TLS


$mail->SMTPSecure = 'ssl';

#$mail->SMTPSecure = 'tls';


$mail->SMTPAuth = true;


$mail->Username = "your.google@gmail.com";


$mail->Password = "xxxxxxxxxxxxxxxx";


$mail->setFrom('your.google@gmail.com', 'from');


$mail->addAddress('mailto@mailto.domain', 'mailto');


$mail->Subject = 'PHPMailer GMail SMTP test';


$mail->Body = 'This is the HTML message body in bold!';


if (!$mail->send()) {

    echo "Mailer Error: " . $mail->ErrorInfo;

} else {

    echo "Message sent!";

}

?>