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.me
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}"
Laravel 9 Send Mail using Gmail SMTP Server
MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=my_name@gmail.com MAIL_PASSWORD=my_gmail_password MAIL_ENCRYPTION=tls MAIL_FROM_ADDRESS=mygoogle@gmail.com MAIL_FROM_NAME="${APP_NAME}"
fichero config/mail.php
añadir 2 líneas al final de la configuración de mailer:
'auth_mode' => null, 'verify_peer' => false
nano config\mail.php
<?php return [ /* |-------------------------------------------------------------------------- | Default Mailer |-------------------------------------------------------------------------- | | This option controls the default mailer that is used to send any email | messages sent by your application. Alternative mailers may be setup | and used as needed; however, this mailer will be used by default. | */ 'default' => env('MAIL_MAILER', 'smtp'), /* |-------------------------------------------------------------------------- | Mailer Configurations |-------------------------------------------------------------------------- | | Here you may configure all of the mailers used by your application plus | their respective settings. Several examples have been configured for | you and you are free to add your own as your application requires. | | Laravel supports a variety of mail "transport" drivers to be used while | sending an e-mail. You will specify which one you are using for your | mailers below. You are free to add additional mailers as required. | | Supported: "smtp", "sendmail", "mailgun", "ses", | "postmark", "log", "array", "failover" | */ 'mailers' => [ 'smtp' => [ 'transport' => 'smtp', 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), 'port' => env('MAIL_PORT', 587), 'encryption' => env('MAIL_ENCRYPTION', 'tls'), 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), 'timeout' => null, 'local_domain' => env('MAIL_EHLO_DOMAIN'), 'auth_mode' => null, 'verify_peer' => false, ], 'ses' => [ 'transport' => 'ses', ], 'mailgun' => [ 'transport' => 'mailgun', ], 'postmark' => [ 'transport' => 'postmark', ], 'sendmail' => [ 'transport' => 'sendmail', 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'), ], 'log' => [ 'transport' => 'log', 'channel' => env('MAIL_LOG_CHANNEL'), ], 'array' => [ 'transport' => 'array', ], 'failover' => [ 'transport' => 'failover', 'mailers' => [ 'smtp', 'log', ], ], ], /* |-------------------------------------------------------------------------- | 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'), ], /* |-------------------------------------------------------------------------- | 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'), ], ], ];
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.alumnoportada.com.es/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:
Más información:
Mail send in Laravel
Manejo de correo entrante en Laravel
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.