通過PHP直接發(fā)送郵件是我們程序員實現(xiàn)會員注冊, 通知提醒經(jīng)常實現(xiàn)的一個功能, 然要直接做一個PHP郵件發(fā)送類, 那就是一件麻煩的事了, 其實完全自己做也沒有那個必要, 因為網(wǎng)上已經(jīng)有很好的郵件類了, 比如PHPMailer, 這里直接加載TP5下加載及使用方法:
1. 下載: 在項目下直接運行 composer require phpmailer/phpmailer
2. 建立一個控制器, 包含PHPMailer命名空間
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
3. 直接使用
namespace app\controller; use think\Controller; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; class Mailqqtest extends Controller { public function index() { $mail = new PHPMailer(true); try { //Server settings $mail->SMTPDebug = 0;
// Enable verbose debug output $mail->CharSet='UTF-8'; $mail->isSMTP();
// 使用SMTP服務(wù)// Set mailer to use SMTP $mail->Host = 'smtp.qq.com';
// 發(fā)送方的SMTP服務(wù)器地址// Specify main and backup SMTP servers $mail->SMTPAuth = true;
// 是否使用身份驗證// Enable SMTP authentication $mail->Username = '3168765867';
// 發(fā)送方的QQ郵箱用戶名,就是自己的郵箱名// SMTP username $mail->Password = 'sdfsdfdsfsdf';
// 發(fā)送方的郵箱密碼,不是登錄密碼,是qq的第三方授權(quán)登錄碼,要自己去開啟,在郵箱的設(shè)置->賬戶->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù) 里面// SMTP password, 阿里去企業(yè)郵箱, 就是登陸密碼了 $mail->SMTPSecure = 'ssl';
// 使用ssl協(xié)議方式,// Enable TLS encryption, `ssl` also accepted $mail->Port = 465;
// QQ郵箱的ssl協(xié)議方式端口號是465/587 // TCP port to connect to //Recipients $mail->setFrom('[email protected]', 'zhuangzi');
// 設(shè)置發(fā)件人信息,如郵件格式說明中的發(fā)件人, $mail->addAddress('[email protected]', 'Carl'); // Add a recipient // $mail->addAddress('[email protected]'); // Name is optional // $mail->addReplyTo('[email protected]', '蘇建莊');
// 設(shè)置回復(fù)人信息,指的是收件人收到郵件后,如果要回復(fù),回復(fù)郵件將發(fā)送到的郵箱地址 // $mail->addCC('[email protected]');
// 設(shè)置郵件抄送人,可以只寫地址,上述的設(shè)置也可以只寫地址(這個人也能收到郵件) //$mail->addBCC('[email protected]');
// 設(shè)置秘密抄送人(這個人也能收到郵件) //Attachments $mail->addAttachment(ROOT_PATH.'public/uploads/20170614/151faab81b21708da697f5ec566dc4ad.jpg'); //添加附件 Add attachments $mail->addAttachment(ROOT_PATH.'public/images/01.gif', '附件圖片.gif'); // Optional name //Content $mail->isHTML(true);
// Set email format to HTML $mail->Subject = '郵箱發(fā)送測試';
// 郵件標(biāo)題 $mail->Body = '這里是郵件信息主題';
// 郵件正文 // $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
// 這個是設(shè)置純文本方式顯示的正文內(nèi)容,如果不支持Html方式,就會用到這個,基本無用 $mail->send(); echo '郵箱已經(jīng)被發(fā)送'; } catch (Exception $e) { echo '郵件發(fā)送失敗'; echo 'Mailer Error: ' . $mail->ErrorInfo; } // return "郵箱測試"; }