How can one ensure the security and reliability of email sending functionality in PHP forms, especially when handling user-submitted data?

To ensure the security and reliability of email sending functionality in PHP forms when handling user-submitted data, it is crucial to sanitize and validate the input data before sending the email. This can be achieved by using PHP filters to sanitize user input and implementing proper email validation to prevent injection attacks. Additionally, using a secure email transport method like SMTP with authentication can enhance the security of email sending functionality.

// Sanitize and validate user input data
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);

// Validate email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Handle invalid email address error
}

// Set up email parameters
$to = "recipient@example.com";
$subject = "Contact Form Submission";
$message = "Name: $name\nEmail: $email\nMessage: {$_POST['message']}";

// Send email using SMTP with authentication
$transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
    ->setUsername('your_username')
    ->setPassword('your_password');

$mailer = new Swift_Mailer($transport);

$message = (new Swift_Message($subject))
    ->setFrom([$email => $name])
    ->setTo([$to])
    ->setBody($message);

$result = $mailer->send($message);

if ($result) {
    echo "Email sent successfully.";
} else {
    echo "Failed to send email.";
}