What are the recommended PHP libraries or classes for sending emails, and how can they be integrated into existing code effectively?

Sending emails in PHP can be easily achieved using libraries such as PHPMailer or Swift Mailer. These libraries provide a more robust and reliable way to send emails compared to using the built-in mail function in PHP. To integrate these libraries into existing code effectively, you can download the library files, include them in your PHP script, and use their functions to send emails.

// Include the PHPMailer autoloader
require 'vendor/autoload.php';

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

// Set up the email parameters
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'yourpassword';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->Subject = 'Test Email';
$mail->Body = 'This is a test email';

// Send the email
if ($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Email could not be sent';
}