$to = "recipient@example.com"; $subject = "Subject"; $message = "Hello, this is a test email message"; $headers = "From: sender@example.com\r\n" . "Reply-To: sender@example.com\r\n" . "X-Mailer: PHP/" . phpversion(); mail($to, $subject, $message, $headers);
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); try { $mail->SMTPDebug = 0; $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'user@example.com'; $mail->Password = 'secret'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; $mail->setFrom('sender@example.com', 'Sender Name'); $mail->addAddress('recipient@example.com', 'Recipient Name'); $mail->isHTML(true); $mail->Subject = 'Subject'; $mail->Body = 'Hello, this is a test email message.'; $mail->AltBody = 'Hello, this is a test email message.'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo; }
require_once 'lib/swift_required.php'; $transport = Swift_SmtpTransport::newInstance('smtp.example.com', 587) ->setUsername('user@example.com') ->setPassword('secret'); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance('Subject') ->setFrom(array('sender@example.com' => 'Sender Name')) ->setTo(array('recipient@example.com' => 'Recipient Name')) ->setBody('Hello, this is a test email message', 'text/html'); $result = $mailer->send($message); if($result) { echo 'Message has been sent'; } else { echo 'Message could not be sent'; }In conclusion, PHP mail() function is adequate for basic email functionality but PHP libraries such as PHPMailer and Swiftmailer offer more features and flexibility for sending emails in PHP.