一,安装扩展包
这里我们用的是 phpmailer 这个扩展包,这个是 链接文档:
http://packagist.p2hp.com/packages/phpmailer/phpmailer
直接指令:
composer require phpmailer/phpmailer
然后我们安装完毕之后就是调用这个扩展类了,这里我是用一个总的控制器来管理项目中邮件发送功能。所以我们生成一个邮件控制器:
php artisan make:controller EmailController
二,配置 Gmail
在 EmailController 控制器中我们引用这个类,然后配置一下类
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
class EmailController extends Controller
{
/*
* 发送邮件
* $email 收件人邮箱地址;$title 标题;$body 邮件内容
*/
public static function sendEmail($email,$title,$body) {
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'yourEmailAddress@gmail.com'; // 你的邮箱地址
$mail->Password = 'yourEmailPassword'; // 邮箱密码
$mail->Port = 465; // 端口
$mail->SMTPSecure = 'ssl';
$mail->SMTPDebug = 1;
//Recipients
$mail->setFrom('yourEmailAddress@gmail.com', 'Mailer'); // 发送邮箱
$mail->addAddress($email, 'Dear member'); // 发给谁
$mail->addReplyTo('yourEmailAddress@gmail.com', 'Information'); // 回复邮箱
// Attachments // 附件
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // 发送内容为 html 标签
$mail->Subject = "$title";
$mail->Body = "$body";
$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. Mailer Error: {$mail->ErrorInfo}";
}
}
}
三,发送邮件
配置好我们的 EmailController 之后,我们就可以简单的发送邮件了
$email = test@gmail.com // 更改为实际的邮箱地址
$title = "hello world!";
$body = "<h1>This is a test email!</h1>";
EmailController::sendEmail($email,$title,$body);
四,注意事项
1,要使用 gmail 邮箱发送,首先确定能够连接外网(你懂得),而且要有 gmail 邮箱账号
2,要设置 Gmail 账户开放发送邮件功能
gmail.png
3,把这个配置打开用谷歌浏览器,不打开好像用不了
https://myaccount.google.com/lesssecureapps?pli=1
gmail_1.png
4,有时候你长时间不登录,登录之后发现发送不了邮件,并且你的代码根本没有动,那么可能是下面这个链接的问题:
https : //accounts.google.com/b/0/DisplayUnlockCaptcha
shagnhao这个链接来自此文章:
http://www.queryadmin.com/1012/smtp-error-password-command-failed-534-5-7-14/













网友评论