Laravel Email Sending Configuration 5.1

Asked

Viewed 529 times

1

I need to implement a configuration screen, where the user can set the data to send email as: MAIL_DRIVER, MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, MAIL_ENCRYPTION, etc. In this case the system will not get this information from the Laravel configuration file, but from the database.

Someone knows a way to do that?

1 answer

1

Do the following:

Log in https://mailtrap.io/ and create an account. After that, open the file .env and set the following settings:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=nome de usuario gerado no mailtrap
MAIL_PASSWORD=senha gerada no mailtrap
MAIL_ENCRYPTION=null
MAIL_FROM_NAME="Nome de Envio"
[email protected]

Then in the file Routes/web.php add:

Route::get('pagina/enviar-email/{id}', 'NomeDoController@sendMail')->name('nome.da.rota.aqui');

After that, open your terminal and enter the command php Artisan make:mail Send email . You will create the Send email file in the folder named as Mail in App/Http.

After this, leave the file exactly as the code below:

<?php

namespace App\Mail;

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

class EnviarMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
        * Armazena os campos que serão enviados.
        *
        * @access protected
        * @property array $inputs
        */
    protected $inputs;

    /**
        * Cria uma nova instância e
        * armazena os valores dos campos
        * a serem enviados.
        *
        * @access public
        * @param array $inputs
        * @return void
        */
    public function __construct(array $inputs)
    {
        $this->inputs = $inputs;
    }

    /**
        * Constrói o e-mail a ser enviado.
        * 
        * @access public 
        * @param void
        * @uses view()
        * @return $this
        */
    public function build()
    {
        /**
        * Utiliza uma view qualquer definida, 
        * e atribui a ela os valores 
        * a serem enviados por email.
        *
        **/
        return $this->view('caminho.da.view.aqui')
        ->with(['campo' => $this->inputs]);

} }

Build the view which will be used to send the email next to the fields:

<h1>E-mail de Contato</h1>
<p>Apenas um E-mail</p>

<ul>
    <li>Nome: {{ $campo->nome }}</li>
    <li>E-mail: {{ $campo->email }}</li>
    <li>Login: {{ $campo->valor1 }}</li>
    <li>Senha: {{ $campo->valor2 }}</li>
</ul>

In the Controller, add this method:

/**
* Executa envio de e-mail.
*
* @access public 
* @param int $id
* @uses Mail::to()
* @uses Session:flash()
* @throws Exception
* @return Route
**/
public function sendMail(int $id)
{
    /**
    * Mail pode gerar uma exceção, devido a isso
    * executamos o envio com intuito de capturá-la
    * e posteriormente tratá-la.
    **/
    try{
        Mail::to('[email protected]')->send( new EnviarEmail( NomeDoModel::find($id) ) ) ;
        // Mostra uma mensagem de sucesso se enviado
        Session::flash('success', 'E-mail enviado com sucesso!');
    }catch(Exception $e){
        // Mostra uma mensagem de falha senão enviado
        Session::flash('fail', 'Não foi possível enviar o e-mail!');
    }

    // Redireciona após envio ou falha.
    return redirect()->route('nome.da.rota.aqui', $id);
}

If it works or not, give feedback.

Note: The mailtrap settings can be replaced with the one you want. I used mailtrap only for the purpose of testing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.