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

MaxSky
• 阅读 1809

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 下进行修改方可预览。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这