Tag Archives: email address

PHP Function to Extract an E-mail from a String Programming 31 MAR 2013

kung-fu-php-logoGiven a string, it would often be quite useful to extract any e-mail addresses that it might contain. Luckily for us, PHP makes this fairly trivial through the use of its powerful filter_var functionality.

Essentially the plan of attack is to take the string, tokenize it by breaking it up on the space character (or whatever other delimiters you wish to use), and then loop through each one of those tokens and check if it matches a recognised email address pattern.

Putting all of this together, we would get a function which looks a little like this:

function email_address_extraction($message){
    foreach(preg_split('/ /', $message) as $token) {
        $email = filter_var(filter_var($token, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);
        if ($email !== false) {
            $emails[] = $email;
    return $emails;

To test:

$testmessage = "hello world.  can jon.kabal@image.com, craig.lot+blog@google.com, and roar@hype.com come over   and play?";
$result = email_address_extraction($testmessage);
$testmessage = " craiglot@doe.co.za";
$result = email_address_extraction($testmessage);


How to Add a CC E-mail Address with PHPMailer Programming 02 APR 2012

I’ve moved to the fantastic PHPMailer PHP class to handle all my e-mail send outs for my projects and have thus far been quite impressed by the ease-of-use and robustness of the class.

Today’s code snippet will show you just how easy it is to add CC (“carbon copy” or “courtesy copy” depending in what era you were born!) e-mail addresses to a e-mail send out, thus saving computing time by pushing out a single mail send instead of a number of separate ones for each attached address (well technically, we’re just foisting all the work onto the SMTP server, but still, less work that the web server needs to do, i.e. a win for us!).

In code:

//create the mail class and fill in all the required settings
$mail = new PHPMailer();
$mail->Host = "smtp.server.net";
$mail->SMTPAuth = true;
$mail->Username = "username@domain.com";
$mail->Password = "password1";
$mail->From = "username@domain.com";
$mail->FromName = "Software Simian";
$mail->AddAddress("targetguy@domain.com", "Target Guy");
$mail->AddReplyTo("username@domain.com", "Software Simian");
$mail->Subject = "Subject";
$mail->Body = "Message";
$mail->AltBody = strip_tags("Message:);
//and now for the actual bit of adding multiple CC e-mail addresses
//and send. Now was that not easy?
    $resultstatus = 'Failed';

The code above will result in a mail being sent out to four addresses instead of just the main specified address.