How To Can Send Emails Using PHPMailer In Laravel 11

Sending emails in Laravel using PHPMailer involves integrating PHPMailer library into your Laravel application and configuring it to work with your email provider. PHPMailer is a popular library that provides a simple and flexible way to send emails via PHP. Here’s how you can send emails using PHPMailer in Laravel:

Installation

  1. Install PHPMailer: You can install PHPMailer via Composer by running the following command in your terminal:
   composer require phpmailer/phpmailer

Configuration

  1. Create Mail Configuration: In Laravel, you typically configure email settings in the config/mail.php file. However, since we’re using PHPMailer, we’ll need to configure it separately. Create a new PHPMailer configuration file, such as config/phpmailer.php.
  2. Configure PHPMailer: In the PHPMailer configuration file, you’ll set up your email provider’s SMTP settings. This includes specifying the host, port, username, password, and other relevant settings.

Usage

  1. Create a Mailable Class (Optional): In Laravel, you can create mailable classes to encapsulate email messages and send them using different email drivers. You can create a mailable class using the make:mail Artisan command:
   php artisan make:mail MyMail
  1. Write Email Logic: Inside your mailable class or controller method, write the logic to send the email using PHPMailer. This typically involves creating a new instance of PHPMailer, configuring it with the necessary settings, setting the email subject, body, recipients, attachments, etc., and then sending the email.
   use PHPMailer\PHPMailer\PHPMailer;
   use PHPMailer\PHPMailer\Exception;

   // Create a new PHPMailer instance
   $mail = new PHPMailer(true);

   try {
       //Server settings
       $mail->isSMTP();
       $mail->Host = 'smtp.example.com';
       $mail->SMTPAuth = true;
       $mail->Username = 'your_username@example.com';
       $mail->Password = 'your_password';
       $mail->SMTPSecure = 'tls';
       $mail->Port = 587;

       //Recipients
       $mail->setFrom('from@example.com', 'Mailer');
       $mail->addAddress('recipient@example.com', 'Recipient');

       //Content
       $mail->isHTML(true);
       $mail->Subject = 'Subject';
       $mail->Body = 'Body';

       $mail->send();
       echo 'Message has been sent';
   } catch (Exception $e) {
       echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
   }

Conclusion

Using PHPMailer in Laravel provides a powerful and flexible way to send emails in your applications. By following the installation, configuration, and usage steps outlined above, you can easily integrate PHPMailer into your Laravel application and start sending emails with ease. Whether you’re sending simple text emails or complex HTML messages with attachments, PHPMailer can handle it all efficiently.

Leave a Reply