How do I send emails in PHP (mail, PHPMailer, Symfony Mailer)?

PHP, mail, PHPMailer, Symfony Mailer, email sending, web development, backend
This content provides examples and methods for sending emails in PHP using native functions and popular libraries like PHPMailer and Symfony Mailer.
// Using PHP mail function $to = 'recipient@example.com'; $subject = 'Test Email'; $message = 'Hello! This is a test email.'; $headers = 'From: sender@example.com' . "\r\n" . 'Reply-To: sender@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); if(mail($to, $subject, $message, $headers)) { echo 'Email sent successfully!'; } else { echo 'Email sending failed.'; } // Using PHPMailer use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; // Load Composer's autoloader $mail = new PHPMailer(true); try { $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'user@example.com'; $mail->Password = 'secret'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; // Recipients $mail->setFrom('from@example.com', 'Mailer'); $mail->addAddress('recipient@example.com'); // Content $mail->isHTML(true); $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body in bold!'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } // Using Symfony Mailer use Symfony\Component\Mailer\Mailer; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Email; // Create a Transport (e.g., for SMTP) $transport = (new \Symfony\Component\Mailer\Transport\SmtpTransport('smtp.example.com', 587, 'tls')) ->setUsername('username') ->setPassword('password'); $mailer = new Mailer($transport); $email = (new Email()) ->from('from@example.com') ->to('recipient@example.com') ->subject('Subject Here') ->text('This is the plain text version of the email') ->html('

This is the HTML version of the email

'); $mailer->send($email); echo 'Email sent successfully with Symfony Mailer!';

PHP mail PHPMailer Symfony Mailer email sending web development backend