[PHP] 使用PHPMailer線上發信通過驗證的SMTP

這個 PHPMailer 滿好用的,可以用 Gmail 的帳號來寄信。也可以放到 wordpress 資料夾裡和 wordpress 一起運作。

Github: https://github.com/PHPMailer/PHPMailer

 

取得 source code 的方法有 2種,一個是去github download 另一個是透過指令:

composer require phpmailer/phpmailer

如果沒有 composer 指令,在 RedHat/CentOS 是用 yum install composer 就可以有這個指令。

附註:執行 composer 指令,必需是一般使用者,不能是 root. 一般使用者的檔案如果要開放給其他使用者去存取,請一一檢查所有的 parent folder 權限都有開 read, 這樣子 apache:apache 帳號的人才能讀的到 php source code.


官方的範例1號:

<?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\Exception;

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

$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 = 'smtp1.example.com;smtp2.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]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
    $mail->addAddress('[email protected]');               // Name is optional
    $mail->addReplyTo('[email protected]', 'Information');
    $mail->addCC('[email protected]');
    $mail->addBCC('[email protected]');

    //Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //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;
}

You’ll find plenty more to play with in the examples folder.

That’s it. You should now be ready to use PHPMailer!


民間範例 2號:

<?php
include(“PHPMailerAutoload.php”); //匯入PHPMailer類別

$mail= new PHPMailer(); //建立新物件
$mail->IsSMTP(); //設定使用SMTP方式寄信
$mail->SMTPAuth = true; //設定SMTP需要驗證
$mail->Host = “XXX.XXX.XXX.XXX”; //設定SMTP主機
$mail->Port = 25; //設定SMTP埠位,預設為25埠
$mail->CharSet = “big5”; //設定郵件編碼

$mail->Username = “*********”; //設定驗證帳號
$mail->Password = “*********”; //設定驗證密碼

$mail->From = [email protected]; //設定寄件者信箱
$mail->FromName = “測試人員”; //設定寄件者姓名

$mail->Subject = “PHPMailer 測試信件”; //設定郵件標題
$mail->Body = “大家好, 這是一封測試信件! “; //設定郵件內容
$mail->IsHTML(true); //設定郵件內容為HTML
$mail->AddAddress(“[email protected]”, “Max”); //設定收件者郵件及名稱
if(!$mail->Send()) {
echo “Mailer Error: ” . $mail->ErrorInfo;
} else {
echo “Message sent!”;
}
?>

上面範例,直接使用會有錯誤,需要參考上面 1號的範例,使用單引號在 Password 裡就會一切正常。


整合用的範例 3號:

As the others said, you can’t. You can find good examples of HTML-php forms on the web, here’s a very useful link that combines HTML with javascript for validation and php for sending the email.

Please check the full article (includes zip example) in the source: http://www.html-form-guide.com/contact-form/php-email-contact-form.html

HTML:

<form method="post" name="contact_form"
action="contact-form-handler.php">
    Your Name:
    <input type="text" name="name">
    Email Address:
    <input type="text" name="email">
    Message:
    <textarea name="message"></textarea>
    <input type="submit" value="Submit">
</form>

JS:

<script language="JavaScript">
var frmvalidator  = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email",
  "Please enter a valid email address");
</script>

PHP:

<?php
$errors = '';
$myemail = '[email protected]';//<-----Put Your email address here.
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['message']))
{
    $errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email_address\n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>

 

 


附註: 所以要將 /etc/php.ini 中的 extension=php_openssl.dll 前面的分號(;)拿掉, 這個我沒有去拿,不知是不是新版本的 php 7.0 已內建支援 openssl.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *