简体   繁体   English

如何在使用 Laravel 在控制器中发送邮件之前更改邮件配置?

[英]How to change mail configuration before sending a mail in the controller using Laravel?

I'm using Laravel 4, I would like to change the mail configuration (like driver/host/port/...) in the controller as I would like to save profiles in databases with different mail configuration.我正在使用 Laravel 4,我想更改控制器中的邮件配置(如驱动程序/主机/端口/...),因为我想将配置文件保存在具有不同邮件配置的数据库中。 This is the basic send mail using configuration from config/mail.php这是使用 config/mail.php 配置的基本发送邮件

Mail::send(
    'emails.responsable.password_lost',
    array(),
    function($message) use ($responsable){
        $message->to($responsable->email, $responsable->getName());
        $message->subject(Lang::get('email.password_lost'));
    });

I've tried to put something like but it didn't work我试过放一些类似的东西,但没有用

 $message->port('587');

Thanks for your support!谢谢您的支持!

Jean

You can set/change any configuration on the fly using Config::set :您可以使用Config::set即时设置/更改任何配置:

Config::set('key', 'value');

So, to set/change the port in mail.php you may try this:因此,要在mail.php设置/更改端口,您可以尝试以下操作:

Config::set('mail.port', 587); // default

Note: Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.注意:在运行时设置的配置值只针对当前请求设置,不会延续到后续请求。 Read more .阅读更多

Update :A hack for saving the config at runtime.更新在运行时保存配置的技巧。

The selected answer didn't work for me, I needed to add the following for the changes to be registered.所选答案对我不起作用,我需要添加以下内容以进行更改。

Config::set('key', 'value');
(new \Illuminate\Mail\MailServiceProvider(app()))->register();

I know is kind of late but an approach could be providing a swift mailer to the laravel mailer.我知道有点晚了,但一种方法可能是为 laravel 邮件程序提供一个快速邮件程序。

<?php

$transport = (new \Swift_SmtpTransport('host', 'port'))
    ->setEncryption(null)
    ->setUsername('username')
    ->setPassword('secret');

$mailer = app(\Illuminate\Mail\Mailer::class);
$mailer->setSwiftMailer(new \Swift_Mailer($transport));

$mail = $mailer
    ->to('user@laravel.com')
    ->send(new OrderShipped);

If you want to create a Laravel 7 application where users are allowed to register and sign in on your application and you intend to enable each user with the ability to send emails through your platform, using their own unique email address and password.如果您想创建一个Laravel 7应用程序,允许用户在您的应用程序上注册和登录,并且您打算让每个用户能够使用他们自己唯一的电子邮件地址和密码通过您的平台发送电子邮件。

THE SOLUTION:解决方案:

  1. Laravel Model : first you'll need to create a database table to store the user's email configuration data. Laravel模型:首先您需要创建一个数据库表来存储用户的电子邮件配置数据。 Next, you'll need an Eloquent Model to retrieve an authenticated user's id to fetch their email configuration data dynamically.接下来,您需要一个Eloquent 模型来检索经过身份验证的用户的 id 以动态获取他们的电子邮件配置数据。
  2. Laravel ServiceProvider : next, create a service provider that would query the database for the user's email configurations using a scope method within your Model class and would set it as their default mail configuration. Laravel ServiceProvider :接下来,创建一个服务提供者,该服务提供者将使用Model类中的 scope 方法在数据库中查询用户的电子邮件配置,并将其设置为他们的默认邮件配置。 Do not register this service provider within your config/app.php不要在你的config/app.php注册这个服务提供者
  3. Laravel MiddleWare : also create a middleware that would run when a user has been authenticated and register the ServiceProvider . Laravel MiddleWare :还创建一个中间件,当用户通过身份验证并注册ServiceProvider 时运行

IMPLEMENTING THE MODEL :实施模型

Make a migration.进行迁移。 Run these from the command line php artisan make:migration create_user_email_configurations_table .从命令行运行这些php artisan make:migration create_user_email_configurations_table Then:然后:

Schema::create('user_email_configurations', function (Blueprint $table) {
  $table->id();
  $table->string('user_id');
  $table->string('name');
  $table->string('address');
  $table->string('driver');
  $table->string('host');
  $table->string('port');
  $table->string('encryption');
  $table->string('username');
  $table->string('password');
  $table->timestamps();
});

Finalize and create your model.完成并创建您的模型。 Run php artisan migrate and php artisan make:model userEmailConfiguration .运行php artisan migratephp artisan make:model userEmailConfiguration Now add a scope method into your model.现在将范围方法添加到您的模型中。

<?php
  namespace App;
  use Illuminate\Support\Facades\Auth;
  use Illuminate\Database\Eloquent\Model;

class userEmailConfiguration extends Model
{
  protected $hidden = [
    'driver',
    'host',
    'port',
    'encryption',
    'username',
    'password'
  ];
  public function scopeConfiguredEmail($query) {
    $user = Auth::user();
    return $query->where('user_id', $user->id);
  }
}

IMPLEMENTING THE SERVICEPROVIDER实施服务提供者

Run this from the command line - php artisan make:provider MailServiceProvider从命令行运行它 - php artisan make:provider MailServiceProvider

<?php
  namespace App\Providers;
  use Illuminate\Support\ServiceProvider;
  use App\userEmailConfiguration;
  use Config;
class MailServiceProvider extends ServiceProvider
{
  public function register()
  {
    $mail = userEmailConfiguration::configuredEmail()->first();
    if (isset($mail->id))
    {
      $config = array(
        'driver'     => $mail->driver,
        'host'       => $mail->host,
        'port'       => $mail->port,
        'from'       => array('address' => $mail->address, 'name' => $mail->name),
        'encryption' => $mail->encryption,
        'username'   => $mail->username,
        'password'   => $mail->password
      );
      Config::set('mail', $config);
    }
  }
  public function boot()
  {
  }
}

IMPLEMENTING THE MIDDLEWARE实现中间件

Run the following command - php artisan make:middleware MailService运行以下命令 - php artisan make:middleware MailService

<?php
  namespace App\Http\Middleware;
  use Closure;
  use App;
class MailService
{
  public function handle($request, Closure $next)
  {
    $app = App::getInstance();
    $app->register('App\Providers\MailServiceProvider');
    return $next($request);
  }
}

Now that we've implemented all that, register your middleware within your $routedMiddleware array in your kennel.php as mail .现在,我们已经实现了这一切,注册您的中间件的内$routedMiddleware在你的阵列kennel.phpmail Then call it up within your authenticated routes middleware:然后在经过身份验证的路由中间件中调用它:

Sample:样本:

Route::group(['middleware' => [ 'auth:api' ]], function () {
  Route::post('send/email', 'Controller@test_mail')->middleware('mail');
});

Here's my original post over medium - Enable Unique And Dynamic SMTP Mail Settings For Each User — Laravel 7这是我在媒体上的原始帖子 - 为每个用户启用唯一和动态的 SMTP 邮件设置 — Laravel 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM