php – send email

使用時需先inlcude “phpmailer.zip” 內的檔案
下載點: 下載點

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';

$mail = new PHPMailer(true);
// $mail->SMTPDebug = 2; //如打開會顯示錯誤信息
$mail->isSMTP();
$mail->Host = "smtp.host"; //設定SMTP
$mail->Port = 25;  //465 = ssl 587 = tls
$mail->SMTPAuth = false;  //加密驗證, 如果是tls/ssl加密 需改為true
$mail->SMTPSecure = false;  //加密方式: ssl or tls or false
$mail->Username = "username";  //SMTP登入帳號
$mail->Password = "password";  //SMTP登入密碼

$mail->setFrom("abc@doamin.com","name"); //設定發信人電郵及名稱
$mail->Subject ="subject";  //郵件主題
$mail->Body = "body";  //郵件內容
$mail->CharSet = "UTF-8";
$mail->Encoding = "base64";
$mail->isHTML(true);  //設定為HTML語法

//新增收件人
$mail->addAddress("a@domain.com");
$mail->addCC("a@domain.com");
$mail->addBCC("c@domain.com");

//發送電郵
$mail->send();


?>

可重用function

common.php下載點

<?php
include "common.php"; //common.php 包括了 read write ini

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$configINI = new INIFile("config.ini");

$mail = new PHPMailer(true);
// $mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = $configINI->readINI("SMTP","HOST");
$mail->Port = $configINI->readINI("SMTP","PORT");


if($configINI->readINI("SMTP","SMTPSECURE") != ""){
	$mail->SMTPAuth = true;
	$mail->SMTPSecure = $configINI->readINI("SMTP","SMTPSECURE");
	$mail->Username = $configINI->readINI("SMTP","USERNAME");
	$mail->Password = $configINI->readINI("SMTP","PASSWORD");
}


function sendEmail($from,$from_name, $to, $subject, $html_body, $cc, $bcc){



	$GLOBALS['mail']->setFrom($from, $from_name);
	$GLOBALS['mail']->Subject = $subject;
	$GLOBALS['mail']->Body = $html_body;
	$GLOBALS['mail']->CharSet = "UTF-8";
	$GLOBALS['mail']->Encoding = "base64";
	$GLOBALS['mail']->isHTML(true);

	//多於1個收件者
	if(strpos($to, ',') !== false){
		$toArr = explode(',', $to);

		for($i = 0;$i < sizeof($toArr); $i++){
			if($toArr[i] == "" || $toArr[i] == null){
				continue;
			}

			$GLOBALS['mail']->addAddress($toArr[i]);
		}

	}
	else{
		$GLOBALS['mail']->addAddress($to);
	}

	//多於1個CC
	if(strpos($cc, ',') !== false){
		$ccArr = explode(',', $cc);

		for($i = 0;$i < sizeof($ccArr); $i++){
			if($ccArr[i] == "" || $ccArr[i] == null){
				continue;
			}

			$GLOBALS['mail']->addCC($ccArr[i]);
		}
	}
	else if($cc != "" && $cc != null){
		$GLOBALS['mail']->addCC($cc);
	}

	//多於1個BCC
	if(strpos($bcc, ',') !== false){
		$bccArr = explode(',', $bcc);

		for($i = 0;$i < sizeof($bccArr); $i++){
			if($bccArr[i] == "" || $bccArr[i] == null){
				continue;
			}

			$GLOBALS['mail']->addBCC($bccArr[i]);
		}
	}
	else if($bcc != "" && $bcc != null){
		$GLOBALS['mail']->addBCC($bcc);
	}


	$GLOBALS['mail']->send();
}


?>

config.ini 例子

[SMTP]
HOST=smtp.domain.com
PORT=465
SMTPSECURE=ssl
USERNAME=username
PASSWORD=password

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部