# PHP - 使用PHPMailer發郵件


PHPMailer支持多種郵件發送方式,使用起來非常簡單

1.下載PHPMailer

https://github.com/PHPMailer/PHPMailer,下載完成加壓后,

把下邊的兩個文件復制進php的根目錄:

2.設置郵件服務器

我們以qq郵箱為例,進入qq郵箱中,點擊設置,選中賬戶選項,在賬戶下設置POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務:

這里提示生成授權碼,點擊生成就行了,需要用手機發短信,之后得到授權碼,保存下來。

3.寫發郵件函數

我們這里的函數只是為了演示功能,大家可以自定義自己的函數

function sendMail($body) {
		//invoke mail() function to send mail
	// mail($toaddress, $subject, $mailcontent, $fromaddress);
	date_default_timezone_set('Asia/Shanghai');//設定時區東八區
    require_once('class.phpmailer.php');
    include('class.smtp.php');
    $mail = new PHPMailer;

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

	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'smtp.qq.com';  // Specify main and backup SMTP servers
	$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = '714034323';                 // SMTP username
	$mail->Password = 'budejddmfejdsedj';                           // SMTP password
	$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
	$mail->Port = 465;  

	echo $mail->Host;                                  // TCP port to connect to

	$mail->setFrom('714034323@qq.com', 'Mailer');
	// $mail->addAddress('714080794@qq.com', 'Joe User');     // Add a recipient
	$mail->addAddress('714034323@qq.com');               // Name is optional
	$mail->addReplyTo('714034323@qq.com', 'Information');
	// $mail->addCC('714034323@qq.com');
	// $mail->addBCC('714034323@qq.com');

	// $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
	// $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
	$mail->isHTML(false);                                  // Set email format to HTML

	$mail->Subject = 'Here is the subject';
	$mail->Body    = $body;
	$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

	if(!$mail->send()) {
	    echo 'Message could not be sent.';
	    echo 'Mailer Error: ' . $mail->ErrorInfo;
	} else {
	    echo ucwords('Message has been sent');
	}
}

4.注意事項

$mail->Host = 'smtp.qq.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '714034323';                 // SMTP username
$mail->Password = 'budejddmfejdsedj';                           // SMTP password
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; 

上邊的設置最重要,Host不能寫錯,qq的郵箱是需要驗證的,所有SMTPAuth設為true,Port按照qq的設置就行了。

5.發郵件

調用函數就能發郵件了,這個函數很多地方都是寫死的,大家可靈活修改。有什么為題,可以留言。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM