How to send mail using phpmailer

PHPMailer is a popular PHP library used to send emails. Here's a step-by-step guide on how to send a mail using PHPMailer:

Step 1: Install PHPMailer

You can install PHPMailer using Composer by running the following command:

composer require phpmailer/phpmailer

Step 2: Include PHPMailer

Include the PHPMailer library in your PHP script:

require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'vendor/autoload.php';

Step 3: Create a PHPMailer Object

Create a new instance of the PHPMailer class:

$mail = new PHPMailer();

Step 4: Set Mail Properties

Set the mail properties such as sender email, recipient email, subject, and body:

$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.example.com'; // Specify a SMTP host
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'your_password'; // SMTP password
$mail->Port = 587; // SMTP port

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer.';

Step 5: Set Attachment (Optional)

If you want to send an attachment, you can use the addAttachment() method:

$mail->addAttachment('path/to/attachment.pdf', 'attachment.pdf');

Step 6: Send the Mail

Send the mail using the send() method:

if (!$mail->send()) {
    echo 'Error sending mail: '. $mail->ErrorInfo;
} else {
    echo 'Mail sent successfully!';
}

Full Code Example

Here's the full code example:

<?php

require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer();

$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.example.com'; // Specify a SMTP host
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = '[email protected]'; // SMTP username
$mail->Password = 'your_password'; // SMTP password
$mail->Port = 587; // SMTP port

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email sent using PHPMailer.';

// Optional: Set attachment
$mail->addAttachment('path/to/attachment.pdf', 'attachment.pdf');

if (!$mail->send()) {
    echo 'Error sending mail: '. $mail->ErrorInfo;
} else {
    echo 'Mail sent successfully!';
}

?>

Make sure to replace the placeholders ([email protected], your_password, [email protected], and path/to/attachment.pdf) with your actual email credentials and attachment path.