在laravel 中使用phpmailer发一个邮件

安装phpmailer

composer require phpmailer/phpmailer

封装一个 phpMail 服务在 services中

<?php
namespace App\Services;
use  PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
class PhpMail
{
    //两个参数,一个收件人,一个邮件内容
    public function send($recipient,$contentString)
    {
        $mail = new PHPMailer(true);
        try {
            $mail->SMTPDebug = 0;  // 调试模式输出
            $mail->CharSet ="UTF-8";    //设定邮件编码 可以不写,默认就是UTF-8
            $mail->isSMTP();  // 使用SMTP
            $mail->Host       = 'smtp.qq.com';  // SMTP服务器
            $mail->SMTPAuth   = true;  // 允许 SMTP 认证
            $mail->Username   = 'xxxxx@qq.com';  // SMTP 用户名  即邮箱的用户名
            $mail->Password   = 'xxxxxxxxxxxx'; // SMTP 密码  部分邮箱是授权码(例如163邮箱)
            $mail->SMTPSecure = 'ssl';  // 允许 TLS 或者ssl协议
            $mail->Port       = 465; // 服务器端口 25 或者465 具体要看邮箱服务器支持
//            发送人是谁,怎么称呼?
            $mail->setFrom('xxxxx@qq.com', '守明大大');
//            要发给谁?用什么来称呼
            $mail->addAddress("$recipient", '尊敬的用户');
//            收件人可以多写几个,可以一并发送
//            $mail->addAddress('ellen@example.com');
            $mail->addReplyTo('1843395688@qq.com', 'reply');
            //内容设置
            //            是否以html格式发送
            $mail->isHTML(true);
            //Set email format to HTML
//            这是邮件标题
            $mail->Subject = '这是给您的一封邮件';
            $mail->Body    = " <b>$contentString</b>";
            $mail->AltBody = "$contentString";
//            发送
            $mail->send();
            return '邮件发送成功';
        } catch (Exception $e) {
            return  "邮件发送失败: {$mail->ErrorInfo}";
        }
  }

}

收件人可以多写几个 ,将 $mail->addAddress("$recipient", '尊敬的用户'); 写在循环中即可

使用


public function test()
{

    $mail=new PhpMail();
  $error=  $mail->send('xxxxxxx@139.com','123456');
    dump($error);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值