Send contact to email with Laravel?

Asked

Viewed 1,009 times

0

This sending all page to e-mail, but does not send the information of input?

Controller

public function store(Request $request) {

    Mail::send('template.contato', 
    array (
        'nome'      => $request -> input('nome'),
        'email'     => $request -> input('email'),
        'assunto'   => $request -> input('assunto'),
        'mensagem'  => $request -> input('mensagem')
    ) , function($message) {
        $message->from('meu email'); // para fazer teste por isso colocando meu email.
        $message->to('meu email')->subject('Mensagem do site');
    });

    return response()->json(['status' => 1, 'msg' => 'Mensagem enviada']);
}

config/email.php

'driver' => 'smtp',
'host'   => 'smtp.gmail.com',
'port'   =>  465,
'from'   => [
    'address' => 'meu email',
    'name' => 'Douglas',
],

'encryption' => 'ssl',
'username'   => 'meu email',
'password'   => 'minha senha',
'sendmail'   => '/usr/sbin/sendmail -bs',
'markdown'   => [
    'theme'  => 'default',
    'paths'  => [
        resource_path('views/vendor/mail'),
    ],
],

Form:

   {{ Form::open(['route' => 'contato.store']) }}

       <div class="form-group">
           {!! Form::label('Nome') !!}
           {!! Form::text('nome', null, array(
                   'required',
                   'class'         =>  'form-control',
                   'id'            =>  'nome')) !!}
       </div>

       <div class="form-group">
           {!! Form::label('Email') !!}
           {!! Form::email('email', null, array(
                    'required',
                    'class'         =>  'form-control',
                    'id'            =>  'email')) !!}
       </div>

       <div class="form-group">
          {!! Form::label('Assunto') !!}
          {!! Form::text('assunto', null, array(
                    'required',
                    'class'         =>  'form-control',
                    'id'            =>  'assunto')) !!}
       </div>

       <div class="form-group">
         {!! Form::label('Mensagem') !!}
         {!! Form::textarea('mensagem', null, array(
                    'required',
                    'class'         =>  'form-control',
                    'id'            =>  'mensagem')) !!}
       </div>

       <div class="text-center">
         <button type="submit" 
                 class="btn btn-primary btn-lg">
          Enviar
         </button>
       </div>
       {!! Form::close() !!}

contact.blade.php

 <div class="container">
        <div class="row">
            <div class="col-lg-6">

                {{ Form::open(['route' => 'contato.store', 'method' => 'POST']) }}

                    <div class="form-group">
                        {!! Form::label('Nome') !!}
                        {!! Form::text('nome', null, array(
                            'required',
                            'class'         =>  'form-control',
                            'id'            =>  'nome')) !!}
                    </div>

                    <div class="form-group">
                        {!! Form::label('Email') !!}
                        {!! Form::email('email', null, array(
                            'required',
                            'class'         =>  'form-control',
                            'id'            =>  'email')) !!}
                    </div>

                    <div class="form-group">
                        {!! Form::label('Assunto') !!}
                        {!! Form::text('assunto', null, array(
                            'required',
                            'class'         =>  'form-control',
                            'id'            =>  'assunto')) !!}
                    </div>

                   <div class="form-group">
                        {!! Form::label('Mensagem') !!}
                        {!! Form::textarea('mensagem', null, array(
                            'required',
                            'class'         =>  'form-control',
                            'id'            =>  'mensagem')) !!}
                    </div>

                    <div class="text-center"><button type="submit" class="btn btn-primary btn-lg">Enviar</button></div>
                {!! Form::close() !!}
            </div>

            <div class="col-lg-6">
                <div class="recent">
                    <h3>Igreja Evangélica Semear</h3>
                </div>
                <div class="">
                    <h4>Endereço:</h4>Rua Três Marias, N° 219, Caruaru-PE.<br>
                    <h4>Telefone:</h4>(81) 99476-1916</br>
                    <h4>Cep:</h4>55032-250
                    <h4>Nosso E-mail:</h4>[email protected]
                </div>                                      
            </div>          
        </div>
    </div>
  • 1

    Cade the template.contato?

  • 1

    I edited the question.

  • 1

    Mail::send('template.contato', you set up so then the page would be template.contato.blade.php is missing her?

  • I don’t know if it helps much... Know that Laravel has a component just for sending emails and is even very easy to use, already consulted the documentation? If not, see here: https://laravel.com/docs/5.2/mail#sending-mail

1 answer

0

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.

The version of the Laravel I used was 5.7 on localhost.

Browser other questions tagged

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