Need help with php mail()...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jconlin
Forum Newbie
Posts: 3
Joined: Sat Jan 26, 2008 2:44 pm

Need help with php mail()...

Post by jconlin »

Newbie here... I have a contact form that is sending via php mail. Everything works perfect EXCEPT that somewhere the "To" field is getting a couple of additional email addresses (related to my server. The code I am using is:

Code: Select all

   
$yourName = 'John';
$yourEmail = 'Doe';
$headers .= 'To: '.$yourName.' <'.$yourEmail.'>'."\r\n";
This is what shows up in email header:

John@69.61.355.445.dedicated.abac.net;Doe@69.61.355.445.dedicated.abac.net;John Doe

Thank you in advance for your help.
dayyanb
Forum Commoner
Posts: 46
Joined: Wed Jan 23, 2008 12:34 am

Re: Need help with php mail()...

Post by dayyanb »

Could you post your whole code please?

From what you said the only thing I could think of is that

Code: Select all

$headers .= 'To: '.$yourName.' <'.$yourEmail.'>'."\r\n";
is somehow being called twice.
jconlin
Forum Newbie
Posts: 3
Joined: Sat Jan 26, 2008 2:44 pm

Re: Need help with php mail()...

Post by jconlin »

This is an Ajax contact form that utilizes several different files (2 php & 3 js) with code for this form. This is everything I am using from my form:

contact.php:

Code: Select all

<?php
// Change the 4 variables below
$yourName = 'Team Potts';
$yourEmail = 'joe@vandigroup.com';
$yourSubject = 'Website Contact Form';
$referringPage = 'http://www.team-potts.com/contact.php';
// No need to edit below unless you really want to. It's using a simple php mail() function. Use your own if you want
function cleanPosUrl ($str) {
return stripslashes($str);
}
    if ( isset($_POST['sendContactEmail']) )
    {
    $to = $yourEmail;
    $subject = $yourSubject.': '.$_POST['posRegard'];
    $message = cleanPosUrl($_POST['posText']);
    $headers = "From: ".cleanPosUrl($_POST['posName'])." <".$_POST['posEmail'].">\r\n";
 
    $mailit = mail($to,$subject,$message,$headers);
        if ( @$mailit ) {
        header('Location: '.$referringPage.'?success=true');
        }
        else {
        header('Location: '.$referringPage.'?error=true');
        }
    }
?>
xmlHttpRequest.php:

Code: Select all

<?php
// change the 4 variables below
$yourName = 'Team Potts';
$yourEmail = 'joe@vandigroup.com';
$yourSubject = 'Website Contact Form';
$referringPage = 'http://www.team-potts.com/contact.php';
// no need to change the rest unless you want to. You could add more error checking but I'm gonna do that later in the official release
 
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
 
echo '<resultset>';
 
function cleanPosUrl ($str) {
$nStr = $str;
$nStr = str_replace("**am**","&",$nStr);
$nStr = str_replace("**pl**","+",$nStr);
$nStr = str_replace("**eq**","=",$nStr);
return stripslashes($nStr);
}
    if ( $_GET['contact'] == true && $_GET['xml'] == true && isset($_POST['posText']) ) {
    $to = $yourName;
    $subject = 'Website Contact Form: '.cleanPosUrl($_POST['posRegard']);
    $message = 'Message: ' . cleanPosUrl($_POST['posText']);
    $headers = "From: ".cleanPosUrl($_POST['posName'])." <".cleanPosUrl($_POST['posEmail']).">\r\n";
    $headers .= 'To: '.$yourName.' <'.$yourEmail.'>'."\r\n";
    $mailit = mail($to,$subject,$message,$headers);
        
        if ( @$mailit )
        { $posStatus = 'OK'; $posConfirmation = 'Success! Your Email has been sent.'; }
        else
        { $posStatus = 'NOTOK'; $posConfirmation = 'Your Email could not be sent. Please try back in a few minutes.'; }
        
        if ( $_POST['selfCC'] == 'send' )
        {
        $ccEmail = cleanPosUrl($_POST['posEmail']);
        @mail($ccEmail,$subject,$message,"From: Yourself <".$ccEmail.">\r\nTo: Yourself");
        }
    
    echo '
        <status>'.$posStatus.'</status>
        <confirmation>'.$posConfirmation.'</confirmation>
        <regarding>'.cleanPosUrl($_POST['posRegard']).'</regarding>
        ';
    }
echo'   </resultset>';
 
?>
contact.js:

Code: Select all

function validateFields() {
var frmEl = document.getElementById('cForm');
var posName = document.getElementById('posName');
var posEmail = document.getElementById('posEmail');
var posRegard = document.getElementById('posRegard');
var posText = document.getElementById('posText');
var strCC = document.getElementById('selfCC');
var whiteSpace = /^[\s]+$/;
    if ( posText.value == '' || whiteSpace.test(posText.value) ) {
        alert("You're trying to send an Empty Email. Please fill out the fields and try again!");
    }
    else if ( posEmail.value == '' && strCC.checked == true ) {
        alert("Oops! You forgot to enter your email...");
        posEmail.focus();
    }
    else {
        sendPosEmail();
    }
}
function sendPosEmail () {
    var success = document.getElementById('emailSuccess');
    var posName = document.getElementById('posName');
    var posEmail = document.getElementById('posEmail');
    var posRegard = document.getElementById('posRegard');
    var posText = document.getElementById('posText');
    var strCC = document.getElementById('selfCC').value;
    var page = "scripts/xmlHttpRequest.php?contact=true&xml=true";
    
    showContactTimer(); // quickly begin the load bar
    success.style.display = 'none'; // hide the success bar (incase this is a multi-email
    
    // convert (&, +, =) to string equivs. Needed so URL encoded POST won't choke.
    var str1 = posName.value;
    str1 = str1.replace(/&/g,"**am**");
    str1 = str1.replace(/=/g,"**eq**");
    str1 = str1.replace(/\+/g,"**pl**");
    var str2 = posEmail.value;
    str2 = str2.replace(/&/g,"**am**");
    str2 = str2.replace(/=/g,"**eq**");
    str2 = str2.replace(/\+/g,"**pl**");
    var str3 = posRegard.value;
    str3 = str3.replace(/&/g,"**am**");
    str3 = str3.replace(/=/g,"**eq**");
    str3 = str3.replace(/\+/g,"**pl**");
    var str4 = posText.value;
    str4 = str4.replace(/&/g,"**am**");
    str4 = str4.replace(/=/g,"**eq**");
    str4 = str4.replace(/\+/g,"**pl**");
    
    var stuff = "selfCC="+strCC+"&posName="+str1+"&posEmail="+str2+"&posRegard="+str3+"&posText="+str4;
    loadXMLPosDoc(page,stuff)
}
function showContactTimer () {
    var loader = document.getElementById('loadBar');
    loader.style.display = 'block';
    sentTimer = setTimeout("hideContactTimer()",6000);
}
 
function hideContactTimer () {
    var loader = document.getElementById('loadBar');
    var success = document.getElementById('emailSuccess');
    var fieldArea = document.getElementById('contactFormArea');
    var inputs = fieldArea.getElementsByTagName('input');
    var inputsLen = inputs.length;
    var tAreas = fieldArea.getElementsByTagName('textarea');
    var tAreasLen = tAreas.length;
    // Hide the load bar alas! Done Loading
    loader.style.display = "none";
    success.style.display = "block";
    success.innerHTML = '<strong>'+grabPosXML("confirmation")+'</strong>';
    // Now Hijack the form elements
    for ( i=0;i<inputsLen;i++ ) {
        if ( inputs[i].getAttribute('type') == 'text' ) {
            inputs[i].value = '';
        }
    }
    for ( j=0;j<tAreasLen;j++ ) {
        tAreas[j].value = '';
    }
}
 
function ajaxContact() {
var frmEl = document.getElementById('cForm');
addEvent(frmEl, 'submit', validateFields, false);
frmEl.onsubmit = function() { return false; }
}
addEvent(window, 'load',ajaxContact, false);
functionAddEvent.js:

Code: Select all

function addEvent(elm, evType, fn, useCapture) {
    if (elm.addEventListener) { 
    elm.addEventListener(evType, fn, useCapture); 
    return true; 
    }
    else if (elm.attachEvent) { 
    var r = elm.attachEvent('on' + evType, fn); 
    EventCache.add(elm, evType, fn);
    return r; 
    }
    else {
    elm['on' + evType] = fn;
    }
}
function getEventSrc(e) {
    if (!e) e = window.event;
 
    if (e.originalTarget)
    return e.originalTarget;
    else if (e.srcElement)
    return e.srcElement;
}
function addLoadEvent(func) {
var oldonload = window.onload;
    if (typeof window.onload != 'function') {
    window.onload = func;
    } else {
    window.onload = 
        function() {
        oldonload();
        func();
        }
    }
}
var EventCache = function(){
    var listEvents = [];
    return {
        listEvents : listEvents,
    
        add : function(node, sEventName, fHandler, bCapture){
            listEvents.push(arguments);
        },
    
        flush : function(){
            var i, item;
            for(i = listEvents.length - 1; i >= 0; i = i - 1){
                item = listEvents[i];
                
                if(item[0].removeEventListener){
                    item[0].removeEventListener(item[1], item[2], item[3]);
                };
                
                /* From this point on we need the event names to be prefixed with 'on" */
                if(item[1].substring(0, 2) != "on"){
                    item[1] = "on" + item[1];
                };
                
                if(item[0].detachEvent){
                    item[0].detachEvent(item[1], item[2]);
                };
                
                item[0][item[1]] = null;
            };
        }
    };
}();
 
 
addEvent(window,'unload',EventCache.flush, false);
xmlHttp.js:

Code: Select all

 
var pos; // variable for posting information
function loadXMLPosDoc(url,posData) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        pos = new XMLHttpRequest();
        pos.onreadystatechange = processPosChange;
        pos.open("POST", url, false);
        pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        pos.send(posData);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        pos = new ActiveXObject("Microsoft.XMLHTTP");
        if (pos) {
            pos.onreadystatechange = processPosChange;
            pos.open("POST", url, false);
            pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            pos.send(posData);
        }
    }
}
 
function grabPosXML (tagName) {
return pos.responseXML.documentElement.getElementsByTagName(tagName)[0].childNodes[0].nodeValue;
}
 
function processPosChange() {
    // page loaded "complete"
    if (pos.readyState == 4) {
        // page is "OK"
        if (pos.status == 200) {
            if ( grabPosXML("posStatus") == 'NOTOK' ) { 
                alert('There were problems Sending Email. Please try again in a couple minutes');
            }
        }
    }
}
dayyanb
Forum Commoner
Posts: 46
Joined: Wed Jan 23, 2008 12:34 am

Re: Need help with php mail()...

Post by dayyanb »

I am a bit confused by these lines in xmlHttpRequest.php:

Code: Select all

 
$yourName = 'Team Potts';
$to = $yourName;
$mailit = mail($to,$subject,$message,$headers);
 
According to php.net the $to variable should be the email address of the person you are sending it to.

I don't see how this would cause the problem you are having though. Am I misunderstanding something?
jconlin
Forum Newbie
Posts: 3
Joined: Sat Jan 26, 2008 2:44 pm

Re: Need help with php mail()...

Post by jconlin »

Thanks for your help. I found the problem in this line:

Code: Select all

   $headers .= '[color=#0040FF]To:[/color] '.$yourName.' <'.$yourEmail.'>'."\r\n";
It should have been:

Code: Select all

   $headers .= '[color=#0040FF]Reply-To:[/color] '.$yourName.' <'.$yourEmail.'>'."\r\n";
Thanks again!
Post Reply