這裏使用的是phpmailer
第三方庫官網 composer
phpmailer 點擊查看官網說明
第一步:下載
你可以使用composer下載
composer require phpmailer/phpmailer
第二步:配置
你可以在公共文件裏面寫一個函數,例:
// 在公共文件中創建函數
<?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;
// 發郵件方法(收件人, 郵件標題, 郵件內容)
function mailSend($to, $title, $content) {
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings 服務器設置
$mail->SMTPDebug = SMTP::DEBUG_OFF;
// 調試等級,0爲關閉
$mail->isSMTP();
// Send using SMTP
$mail->CharSet = 'utf-8';
// 編碼
$mail->Host = 'smtp.qq.com';
// Set the SMTP server to send through 主機
$mail->SMTPAuth = true;
// Enable SMTP authentication
$mail->Username = '[email protected]';
// SMTP username 用戶名
$mail->Password = 'xxxxxxxxxx';
// SMTP password 密碼,其實也不是什麼密碼,大多是授權號
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
// Enable TLS encryption;
// `PHPMailer::ENCRYPTION_SMTPS` encouraged
//裏面有詳細配置,一般使用ssl
$mail->Port = 465;
// TCP port to connect to,
// use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
// 端口,qq使用的是465
//Recipients 收件人
$mail->setFrom('[email protected]', 'Mailer');
// $mail->addAddress('[email protected]', 'Joe User');
// Add a recipient
$mail->addAddress($to); // 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 HTML格式
$mail->Subject = $title; // 標題
$mail->Body = $content; // 內容
// $mail->AltBody = '';
$mail->send(); // 發送
echo 'Message has been sent';
} catch (Exception $e) {
exception($mail->ErrorInfo, 1001); // 發送失敗信息
}
}
配置好後,你就可以調用該函數。
例:
mailSend('[email protected]', '發送測試', '兄弟,不知該號碼是否真實,如果發送成功,純屬巧合!');