Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Sending Emails Tutorial

Introduction

In this tutorial, we will explore how to send emails using Laravel, a popular PHP framework. We will cover the necessary configurations, how to create email templates, and how to send emails through different drivers.

Setting Up Your Laravel Project

First, ensure you have a Laravel project set up. If you don't have one yet, you can create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel email-demo

Configuring Mail Settings

To send emails, you need to configure your mail settings in the .env file located in the root of your Laravel project. Here’s an example configuration using SMTP:

MAIL_MAILER=smtp

MAIL_HOST=smtp.mailtrap.io

MAIL_PORT=2525

MAIL_USERNAME=your_username

MAIL_PASSWORD=your_password

MAIL_ENCRYPTION=null

MAIL_FROM_ADDRESS=example@example.com

MAIL_FROM_NAME="${APP_NAME}"

Make sure to replace your_username and your_password with your actual SMTP credentials. You can use services like Mailtrap or Gmail for testing purposes.

Creating an Email Template

Laravel uses Blade templates for creating emails. You can create a new email template by running the following Artisan command:

php artisan make:mail WelcomeEmail

This command creates a new mailable class in the app/Mail directory. You can customize the email content in the generated class:

public function build()

{

  return $this

    ->subject('Welcome to Our Service')

    ->view('emails.welcome');

}

Next, create the corresponding Blade view for the email in resources/views/emails/welcome.blade.php:

<html>

  <body>

    <h1>Welcome to Our Service!</h1>

    <p>Thank you for joining us. We are glad to have you!</p>

  </body>

</html>

Sending Emails

To send an email, you can use the Mail facade. Here’s an example of sending the welcome email we just created:

use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
Mail::to('user@example.com')->send(new WelcomeEmail());

This code should be placed in a controller or a route closure where you want to trigger the email sending process.

Testing Email Sending

To test if your email sending works, you can set up a route in routes/web.php:

Route::get('/send-email', function () {
  Mail::to('user@example.com')->send(new WelcomeEmail());
  return 'Email sent!';
});

Now, you can visit /send-email in your browser to send the email and check if it was received.

Conclusion

In this tutorial, we covered the basics of sending emails using Laravel. You learned how to configure mail settings, create email templates, and send emails using the Mail facade. With this knowledge, you can now integrate email functionalities into your Laravel applications.