ASMail

This function is used to avoid email injection. Email injection is used to send a lot of spam, so this is essentially Anti-Spam Email.

The Code

I put the code right up front for those who want it. Copy this into your PHP code. I personally save it in a file called asmail.inc and use require_once('asmail.inc') in my common includes section.

	function asmail($to, $subject, $message, $headers=null, $parameters=null) {
		if(filter_var($to, FILTER_VALIDATE_EMAIL) === false) return false;
		$message = str_replace("\n.","\n..",$message);
		$subject = str_replace(array("\r","\n","%0A","%0a","%0D","%0d","0x0A","0x0a","0x0D","0x0d"),'',$subject);
		$ha = explode("\r\n",$headers);
		foreach($ha as $i=>$h)
		{
			$a = explode(':',$h);
			if(sizeof($a) != 2) unset($ha[$i]);
			else $ha[$i] = trim($h);
		}
		$headers = implode("\r\n",$headers);
		return mail($to, $subject, $message, $headers, $parameters);
	}

Usage

This is drop-in replacement for the built-in PHP function mail. See the documentation for mail at http://php.net/manual/en/function.mail.php

Being a drop-in replacement, all you need to do is include this script to make the function available. Then, replace mail(...) with asmail(...) throughout your scripts.

Similar to mail, this will return true if the mail is sent or false if it is not sent.

Notes

This function tries to stop email injection in each parameter of the email, except the extra paramters. To my knowledge, it is not possible to peform injection in the parameters.

The most common form of email injection is to alter the "to" email address. In doing so, a person can get an email to be sent to multiple people. This script uses the built-in filter_var function to ensure that the $to email address is a valid email address.

It is possible to force stops into the subject line to fake the ending of a message and the beginning of a new one. I remove stops from the subject by removing all forms of newlines.

Similar to using stops in the subject line, it is possible to inject stops into the message. They are converted into harmless lines containing two dots.

Extra headers is the big problem that most people struggle to keep clean. I risk throwing away headers by ensuring that every header is in the form: Name: Value. Anything that is not proper is simply removed.

You've read it. You can't unread it.
Copyright ©1998-2017 C. Shaun Wagner. All rights reserved.