Lumen 中配置邮件发送并使用不同发件人发信实例

MaxSky 等级 372 0 0

Intro

阿里网易企业邮发件可参考另一篇:Laravel 6 结合网易/阿里邮箱基本邮件发送功能使用

基本配置

Composer 安装 illuminate/mail 组件后将下方内容保存为 mail.php 放置于 Project/config 目录

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "ses",
    |            "postmark", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'smtp'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Log Channel
    |--------------------------------------------------------------------------
    |
    | If you are using the "log" driver, you may specify the logging channel
    | if you prefer to keep mail messages separate from other log entries
    | for simpler reading. Otherwise, the default channel will be used.
    |
    */

    'log_channel' => env('MAIL_LOG_CHANNEL'),
];

最后在 .env 中新增以下 8 项内容:

# 发信驱动
MAIL_DRIVER=smtp
# 发信服务器
MAIL_HOST=
# 发信端口
MAIL_PORT=465
# 发件人邮箱帐号
MAIL_USERNAME=abc@example.com
# 发件人邮箱密码
MAIL_PASSWORD=password
# 加密方式 ssl/tls
MAIL_ENCRYPTION=tls
# 配置全局默认发件地址
MAIL_FROM_ADDRESS=abc@example.com
# 发件人名称
MAIL_FROM_NAME=张三

服务注册

此处建议在 Project/app/Providers 中注册邮件服务,当然,所有的服务都建议在此注册。

// AppServiceProvider.php

use Illuminate\Contracts\Mail\{Mailer as MailerContract, MailQueue as MailerQueueContract};
use Illuminate\Mail\Mailer;
use Illuminate\Mail\MailServiceProvider;

// function register
$this->app->register(MailServiceProvider::class);

// 下方的 mailer 别名设置与否不影响发信
$this->app->alias('mailer', Mailer::class);
$this->app->alias('mailer', MailerContract::class);
$this->app->alias('mailer', MailerQueueContract::class);

邮件发送

创建模板

Project/resources/views/emails 目录下创建 test.blade.php 文件:

@component('mail::message')
    # 你好

{{ $message }}

@component('mail::button', ['url' => $url])
    打开网站
@endcomponent

感谢,<br>
{{ $app_name }}
@endcomponent

创建邮件类

Project/app/Mail 下新建 TestMail.php 类载入模板

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class TestMail extends Mailable {
    use Queueable, SerializesModels;

    private $data;

    /**
     * Create a new message instance.
     *
     * @param array $data
     */
    public function __construct(array $data = []) {
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build(): InvoiceMail {
        return $this->markdown('emails.test', $this->data);
    }
}

发送

use App\Mail\TestMail;

Mail::to('收件人地址')->send(new TestMail([
    'message' => '测试邮件发送消息',
    'url' => 'https://maxsky.cc',
    'app_name' => '邮件发送项目'
]))

多发件人

举个栗子我们在 .env 中这样配置:(更多同理)

MAIL_A_USERNAME=A@example.com
MAIL_A_PASSWORD=password
MAIL_A_FROM_ADDRESS=A@example.com
MAIL_A_FROM_NAME="名称 A"

MAIL_B_USERNAME=B@example.com
MAIL_B_PASSWORD=password
MAIL_B_FROM_ADDRESS=B@example.com
MAIL_B_FROM_NAME="名称 B"

# etc.

一般情况下,邮件服务注册的是默认配置文件,但我们可以对配置进行临时性修改

取消服务注册

AppServiceProvider.php 中注册的邮件服务我们可以删掉了

创建邮件服务类

Project/app/Services/Common 中创建 MailService 类:(参考,路径可任意)

<?php

namespace App\Services\Common;

use Exception;
use Illuminate\Mail\MailServiceProvider;

class MailService {

    private $type;

    /**
     * @param string $type
     *
     * @return MailService
     */
    public function setFromType(string $type): MailService {
        $this->type = strtoupper($type);
        return $this;
    }

    /**
     * @return void
     * @throws Exception
     */
    public function initSendService(): void {
        if (!$this->type) {
            throw new Exception('Send type not exist.');
        }

        $this->registerProvider($this->getMailAccountConfig($this->type));
    }

    /**
     * @param string $type
     *
     * @return array
     */
    private function getMailAccountConfig(string $type): array {
        $username = env("MAIL_{$type}_USERNAME");
        $password = env("MAIL_{$type}_PASSWORD");
        $fromAddr = env("MAIL_{$type}_FROM_ADDRESS");
        $fromName = env("MAIL_{$type}_FROM_NAME");

        $config = config('mail');

        $config['username'] = $username;
        $config['password'] = $password;
        $config['from']['address'] = $fromAddr;
        $config['from']['name'] = $fromName;

        return $config;
    }

    /**
     * @param array $config
     *
     * @return void
     */
    private function registerProvider(array $config): void {
        // set new mail config
        config(['mail' => $config]);
        // register provider
        app()->register(MailServiceProvider::class);
    }
}

邮件发送

此处用依赖注入的方式实例化服务。

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Mail\TestMail;
use App\Services\Common\MailService;
use Exception;
use Log;
use Mail;

class Test extends Controller {

    private $mailService;

    public function __construct(MailService $mailService) {
        $this->mailService = $mailService;
    }

    public function index() {
        try {
            $this->mailService->setFromType('A')->initSendService();
        } catch (Exception $e) {
            Log::error($e->getMessage());
        }

        Mail::to('收件人地址')->send(new TestMail([
            'message' => '测试邮件发送 A',
            'url' => 'https://maxsky.cc',
            'app_name' => '邮件发送项目'
        ]));

        try {
            $this->mailService->setFromType('B')->initSendService();
        } catch (Exception $e) {
            Log::error($e->getMessage());
        }

        Mail::to('收件人地址')->send(new TestMail([
            'message' => '测试邮件发送 B',
            'url' => 'https://maxsky.cc',
            'app_name' => '邮件发送项目'
        ]));
    }
}

模板预览

更新一个模板预览的方法:

$api->get('preview', function () {
    $mail = new App\Mail\TestMail([
        'message' => '测试邮件发送 A',
        'url' => 'https://maxsky.cc',
        'app_name' => '邮件发送项目'
    ]);

    return $mail->render();
});

然后项目根目录运行 php -S localhost:80 -t public,最后访问 http://localhost/preview 即可。

修改模板

进入 Project/vendor/illuminate/mail/resources/views 目录,将 htmltext 复制到 Project/resources/views/vendor/mail 下进行修改方可预览。

收藏
评论区

相关推荐

php指的是什么?
PHP(全称:Hypertext Preprocessor,即“PHP:超文本预处理器”)是一种开源的通用计算机脚本语言,尤其适用于网络开发并可嵌入H
使用PHP生成网站Sitemap,Laravel风格
PHP生成网站Sitemap,包含默认、分类、文章、标签、profile等 <?php namespace AppLibs; use AppS
nginx安全配置
安全是一个重要的问题,必须引起注意。 1. nginx介绍 nginx本身不能处理PHP(http://www.ttlsa.com/php/ "php"),它只是个web服务器,当接收到请求后,如果是php请求,则发给php解释器处理,并把结果返回给客户端。nginx一般是把请求发fastcgi管理进程处理,fastcgi管理进程选择cgi子
PHP学习笔记之PHP的函数应用
目录一、函数的定义 二、自定义函数 三、函数的工作原理和结构化编程 四、PHP变量的范围 五、声明及应用各种形式的PHP函数 六、递归函数 七、使用自定义函数库 一、函数的定义一个被命名的、独立的代码段,它执行特定的任务,并可能给调用它的程序返回一个值。定义中的各部分如下: 函数是被命名的:每个函数都
Promtheus实战系列(一)之环境部署与搭建
一、部署prometheus,grafana和node\_exporterPrometheus开始教程: 1.1 环境(centos7)root@localhost prometheus uname aLinux localhost.localdomain 3.10
PHP 微信公众号消息加解密
公众号配置根据提示设置即可:【图中信息均为无意义数据,仅供参考。注意服务器地址需可接收 GET/POST 两种请求】 AESKey 直接点一下随机生成即可,Token 可以生成一个 UUID 再把 UUID 进行 MD5 一次即可。 接收关注事件消息示例 请求参数校验这一步根据项目情况,可供参考:(Lumen 框架)php$valida
Nginx 中使用 map 解决多来源跨域问题
map 中需注意,如果存在多个配置文件,不能使用相同的变量名,故这里示例为 $allow_origin_Abash 在 server 上方添加 mapmap $http_origin $allow_origin_A { default ""; "~^(https?://localhost(:\d)?)" $1; "
Windows 下编译 PHP Redis 扩展并支持 Igbinary 序列器
这是 PHP 下扩展的下载地址:当然,通过这个地址我们能够轻松的获取到 Redis 和 Igbinary 扩展并启用,但是,我们可以在页面上打开 phpinfo() 瞧瞧上方截图为重编译的 Redis 扩展,默认情况下通过上方网站下载的 Redis 扩展在 Available serializers 中只有 php 一项。目前仅编译了
Windows 下关于 CURL SSL 证书的放置说明
首先,我们从这个地址摸到 cacert.pem 文件:在 PHP 的配置文件 php.ini 中我们可以搜索 curl.cainfo 并通过填写正确的路径指向使得 Composer、CURL 能够正常请求不过还有一个全局的更合理的方式,通过该链接:在其中搜索 CURL_CA_BUNDLE 我们可以得知:If you're
Lumen 中对 Dingo API 异常接管并自定义响应结果
场景描述比如我们需要对 API 限流抛出的异常进行接管,并重写响应消息,首先应用中间件:phpuse Dingo\Api\Routing\Router;$apigroup( 'middleware' 'api.throttle', // 限流中间件 'expires' 1, // 时间范围,单位“分” 'lim
PHP 中 firebase/php-jwt RS256 公私钥生成指南
所有关于 openssl_sign(): supplied key param cannot be coerced into a private/public key、Algorithm not allowed 等错误按照文章来一遍,基本就能解决了GitHub 用多了,第一反应用 puttygen.exe 这个程序来生成,得到 id_rsa
Lumen 中配置邮件发送并使用不同发件人发信实例
Intro阿里网易企业邮发件可参考另一篇: 基本配置Composer 安装 illuminate/mail 组件后将下方内容保存为 mail.php 放置于 Project/config 目录php<?phpreturn / |
列举一些糟糕的PHP代码
10例糟糕的PHP代码 10例糟糕的PHP代码 这篇文章在很早以前就看到了,由于最近要自己做一些主题方面的东西,代码需要更加规范,用这些反面的例子来约束自己,告诉自己代码不应该这样写,虽然它也能实现功能,但那样做并不明智,
Linux shell(1)
1. 免交互处理在免交互输出处理中可以使用重定向将输出内容输入到黑洞文件/dev/null中。[root@localhost ] echo password | passwd stdin user & /dev/null使用重定向输入将/root/testmail中的内容以Test mail为右键名发送给root@localhost: [root@local
dubbo网关演进之路
本文已收录 https://github.com/lkxiaolou/lkxiaolou 欢迎star。 背景随着公司业务的飞速发展,基于php的模块化架构难以支持未来业务的发展: php模块化架远远落后于行业主流架构(微服务–云原生),而php生态的服务治理开源组件匮乏,研发投入过大 杭州php人才匮乏,导致新鲜血液招聘困难 基于php的多进程架构难以支撑