---
title: Sanitize Input Before Sending Emails
impact: MEDIUM
impactDescription: prevents email header injection and spam abuse
tags: email, injection, sanitization, input-validation, security, kotlin
---

## Sanitize Input Before Sending Emails

Email header injection occurs when an attacker can inject CRLF (Carriage Return + Line Feed) characters into email fields (Subject, From, To, etc.). This allows them to manipulate the SMTP protocol to add their own headers (like `Bcc:` or `Cc:`) and send unauthorized spam via your server.

**Incorrect (unsanitized input):**

```kotlin
// Email injection vulnerability
val subject = request.getParameter("subject") // Attacker: "Hello\r\nBcc: spam@evil.com"
val helper = MimeMessageHelper(message)
helper.setSubject(subject) // Now Bcc: spam@evil.com is part of the email headers!
```

**Correct (sanitized email fields):**

```kotlin
fun sanitizeEmailHeader(input: String): String {
    // Remove all CRLF characters to prevent header injection
    return input.replace("[\r\n]".toRegex(), "").trim()
}

fun isValidEmail(email: String): Boolean {
    val emailRegex = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$".toRegex()
    return emailRegex.matches(email) && !email.contains("\n") && !email.contains("\r")
}

@PostMapping("/api/contact")
fun send(@RequestBody req: ContactRequest) {
    if (!isValidEmail(req.to)) throw ValidationException("Invalid email format")

    val helper = MimeMessageHelper(message)
    helper.setTo(sanitizeEmailHeader(req.to))
    helper.setSubject(sanitizeEmailHeader(req.subject))
    helper.setText(req.body) // Message body is usually safe from header injection
}
```

**Prevention Strategies:**
- **Whitelisting:** Strictly validate email formats.
- **Header Stripping:** Automatically strip or replace all `\r` and `\n` characters from variables that will be used in email headers.
- **Modern Libraries:** Use high-level mailing libraries (like Spring Mail or Ktor Mail) that often perform basic sanitization, but always double-check and manually sanitize user input.

**Tools:** OWASP ESAPI, Hibernate Validator (@Email), Manual Review
