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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

至天

看心情啦,最好留着自己喝奶茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值