Correo en Laravel

Manejo del correo en Laravel

Montar el sistema de ficheros remoto:

sshfs usuario@alumno.xyz:/home/usuario/todo/ servidor -p 22

Conexión al VPS

ssh usuario@alumno.xyz

Enviar mensaje de prueba desde consola (para comprobar el funcionamiento del servidor de correo):

sudo apt install mailutils
mail -s "Email de prueba" paco.portada@protonmail.com <<< "Este es el cuerpo del correo"

Uso de un servidor de correo (Postfix, por ejemplo) en el propio equipo

cd todo
nano .env

Fichero .env (en la carpeta del proyecto de Laravel):

MAIL_MAILER=smtp
MAIL_HOST=localhost
MAIL_PORT=25
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=info@alumno.xyz
MAIL_FROM_NAME="${APP_NAME}"

Envío de un email de prueba

fichero routes/web.php

Route::get('/sendemail', function () {
  try {
    $result = "Your email has been sent successfully";
    $data = array( 'name' => "LearningLaravel.net" );

    Mail::send('emails.learning', $data, function ($message) {
        $from = 'emisor@alumno.xyz';
        $name = 'nombreAlumno';
        // cambiar el email y poner uno propio
        $to = 'nombre@protonmail.com';
        $subject = "Learning Laravel test email";   

        $message->from($from, $name);
        $message->to($to);
        $message->subject($subject);
        });
    } catch (Exception $e) {
            $result = $e->getMessage();
    }

    return $result;
});

Crear el fichero learning.blade.php en la carpeta resources/views/emails:

<!DOCTYPE html>
<html lang="es-ES">
<head>
    <meta charset="utf-8">
</head>
<body>
    <h2>Learning Laravel!</h2>
    <div>
        Bienvenid@ a la web {!! $name !!}!
    </div>
</body>
</html>

Accederemos desde el navegador a la ruta sendemail para hacer el envío:

todo.alumno.xyz/sendemail

 

Formulario de contacto:

Configuración del servidor de correo

nano .env

Fichero .env

MAIL_MAILER=smtp
MAIL_HOST=localhost
MAIL_PORT=25
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=info@alumno.xyz
MAIL_FROM_NAME="${APP_NAME}"

Añadir las rutas en el fichero routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TasksController;
use App\Http\Controllers\EmailController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/', function () {
    return view('welcome');
});

Route::middleware(['auth:sanctum', 'verified'])->group(function(){
    Route::get('/dashboard',[TasksController::class, 'index'])->name('dashboard');

    Route::get('/task',[TasksController::class, 'add']);
    Route::post('/task',[TasksController::class, 'create']);
    
    Route::get('/task/{task}', [TasksController::class, 'edit']);
    Route::post('/task/{task}', [TasksController::class, 'update']);
});

Route::get('/sendemail', function () {
  try {
    $result = "Your email has been sent successfully";
    $data = array( 'name' => "LearningLaravel.net" );
    
    Mail::send('emails.learning', $data, function ($message) {
        $from = 'emisor@alumno.xyz';
        $name = 'nombreAlumno';
        // cambiar el email y poner uno propio
        $to = 'paco.portada@protonmail.com';
        $subject = "Learning Laravel test email";   
        $message->from($from, $name);
        $message->to($to);
        $message->subject($subject);
        });
    } catch (Exception $e) {
            $result = $e->getMessage();
    }
    return $result;
});

Route::get('/email', [EmailController::class, 'create']);
Route::post('/email', [EmailController::class, 'sendEmail'])->name('send.email');

Crear el controlador

php artisan make:controller EmailController

Añadir este contenido al fichero app\Http\Controllers\EmailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;

class EmailController extends Controller
{
    public function create()
    {

        return view('email');
    }

    public function sendEmail(Request $request)
    {
        $request->validate([
          'email' => 'required|email',
          'subject' => 'required',
          'content' => 'required',
        ]);

        $data = [
          'subject' => $request->subject,
          'email' => $request->email,
          'content' => $request->content
        ];

        Mail::send('email-template', $data, function($message) use ($data) {
          $message->to($data['email'])
          ->subject($data['subject']);
        });

        return back()->with(['message' => 'Email successfully sent!']);
    }
}

Crear el fichero resources\views\email.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Mail Send in Laravel</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>

<body>
    <div class="container">
        <h1>Mail Send Example</h1>
          @if(session()->has('message'))
              <div class="alert alert-success">
                  {{ session()->get('message') }}
              </div>
          @endif
        <form action="{{ route('send.email') }}" method="post">
          @csrf
            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="email" class="form-control" placeholder="Enter Email">
                @error('email')
                  <span class="text-danger"> {{ $message }} </span>
                @enderror
            </div>

            <div class="form-group">
                <label>Subject:</label>
                <input type="text" name="subject" class="form-control" placeholder="Enter subject">
                @error('subject')
                  <span class="text-danger"> {{ $message }} </span>
                @enderror
            </div>

            <div class="form-group">
                <strong>Content:</strong>
                <textarea name="content" rows="5" class="form-control" placeholder="Enter Your Message"></textarea>
                @error('content')
                  <span class="text-danger"> {{ $message }} </span>
                @enderror
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-success save-data">Send</button>
                <a href={{ route('dashboard') }}>Return</a>
            </div>
        </form>
    </div>
</body>
</html>

Crear el fichero resources\views\email-template.blade.php

<div class="container">
     <div class="row justify-content-center">
         <div class="col-md-8">
             <div class="card">
                 <div class="card-header">Welcome!</div>
                   <div class="card-body">
                    @if (session('resent'))
                         <div class="alert alert-success" role="alert">
                            {{ __('A fresh mail has been sent to your email address.') }}
                        </div>
                    @endif
                    {!! $content !!}
                </div>
            </div>
        </div>
    </div>
</div>

Accederemos desde el navegador a la ruta email para hacer el envío:

todo.alumno.xyz/email

Más información:

Mail send in Laravel

Manejo de correo entrante en Laravel

 

Deja una respuesta