Back to results for “Input & Validation”
PHP › Email Sending in PHP (PHPMailer & SMTP)

What security considerations should be addressed when building an application feature that sends emails based on user input, such as a contact form or password reset flow?

Advanced

Answer

Security considerations include properly validating and sanitizing any user provided data used within an email, such as a name or message body, to prevent email header injection attacks where a malicious user could manipulate email headers to send spam through your server, rate limiting how frequently a specific user or IP address can trigger email sending to prevent abuse, and never revealing whether a specific email address exists in your system through subtly different response messages, which could otherwise be exploited to enumerate valid user accounts.
// Sanitize input before using it in an email to prevent header injection
$name = str_replace(["\r", "\n"], '', $_POST['name']);
Real-world example A password reset feature always displays the exact same generic confirmation message regardless of whether the submitted email address actually exists in the system, preventing an attacker from using the response to determine which email addresses are registered users.

Common follow-ups: What is email header injection and how does proper input sanitization prevent it?;How do you implement rate limiting specifically for an email sending feature?