What are common pitfalls when trying to store email addresses in a text file and send messages using PHP?

Common pitfalls when storing email addresses in a text file and sending messages using PHP include not properly sanitizing input data, not validating email addresses, and not handling errors effectively. To solve these issues, make sure to validate email addresses before storing them, sanitize input data to prevent SQL injection attacks, and implement error handling to catch any issues that may arise during the sending process.

// Validate and sanitize email address before storing
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Store email address in text file or database
} else {
    // Handle invalid email address
}

// Send email using PHP's mail function
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";

if(mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Failed to send email.";
}