Problem sending mail with PHP mail function

Occasionally I have had trouble sending emails using the builtin mail() function in PHP. Sometimes emails never reached their intended destination. Naturally I have assumed that there might be a problem with some spam filters used. However, lazy as I am, I have not given it a second thought. Instead I have used a PHP class that allows me to send emails using a remote smtp server using an account on that dedicated server. This has been a good solution for my setup anyways. A few days ago a friend of mine was asked to investigate the very same problem for a client.

The problem seems to be that PHP use the ini directive sendmail_from to set the from email address in the SMTP protocol. If this is not correctly set, or if it does not match the from header in the email headers, the email is caught by spam protection software.

The simplest solution is to set the directive during execution:

ini_set("sendmail_from", $email_from);

$headers = "From: $email_from";

mail($to, $subject, $message, $headers);

The problem as well as the solution was already known by others. The operating system this time was windows and I know there are differences in the implementation between the windows and linux version of mail(). I am not sure if the problem exist on both platforms.

Still I bet there are lots of people out there with this problem without them knowing it. It could be a good idea to include more detailed information about this ini entry and its implications in the actual mail() documentation. Sending emails from web pages is, to say the least, a very common task.

Tagged with:
Posted in PHP
48 comments on “Problem sending mail with PHP mail function
  1. pravin says:

    hello sir,
    i m using php in win.There are mail fuctions like ini_set(); is used but its throwing syntex error. i have checked my root directory and functions too.while sending message through e-mail from php.
    is there problem in my server port? please suggest…

    thank’.

  2. pravin says:

    how i can change my SMTP server port. and where i should to use?

  3. Yoke says:

    Hi Pravin,

    Have you tried to check php.ini?
    I might be able to help you if you give me more clues to your problem.
    Or is it already solved? =)

    You can email me with your details (yoke.lee@gmail.com)

  4. James says:

    Hi, I’m using the mail function on one of my web sites, but the mail does not get delivered. I suspect it’s a similar problem as mentioned above as it did not occur on my localhost server.

    I applied your solution, however, it still does not deliver.
    The website is hosted on a web hosting provider so, I don’t have much control over the ini settings.

    Any suggestions?

  5. Justin says:

    Hey James I have the same problem. I have a site using the php mail function and it is hosted by a provider. I don’t know if they know what to do either because I’ve spoke with them several times and we cannot get it to work.

    Any help would be great from anyone.

  6. Yoke says:

    Hi everyone

    When I am working on localhost (Mercury Mail),
    I have to configure the Mercury Mail to point to an existing and working mail server (which happens to be my webhosting server too).
    And I am able to send mail locally.

    Does your webhosting company give you email service?
    You can access to your email account with webmail and do a test there. Just send email to yourself and see if you got it.

    We need more information to analyze, maybe phpinfo() result and php.ini config will do.

    Hope it helps.
    Thanks.

    Yoke Lee

  7. pj says:

    hi,

    i have a somewhat similar problem.

    here’s the scenario:
    (1) using WEBMAIL on server1, sending from domain1 to domain2, domain3 and domain4 is OK.

    (2) using PHP MAIL FUNCTION on server1, sending from domain1 to domain2 FAILS, but sending to domain3 and domain4 is OK.

    have you encountered the same problem? what could possibly be the reason why message sending fails on (2)?

    more details:
    domain1 is on server1 (running whm/cpanel on RHEL 5.2)
    domain2 is on server2 (running whm/cpanel on RHEL 5.2)
    domain3/4 are additional 3rd party domains used to check if mails are received.

    any input you could provide would be most appreciated. cheers!

  8. Danne says:

    Actually I’ve stopped trying. I always send email via external smtp servers now.

  9. pj says:

    oh, i see. too bad. i’ll let you know then if i find a solution.

    by the way, how do you implement the use of external smtp servers? what class are you using?

  10. Danne says:

    I use the builtin classes of Codeigniter or Zend Framework depending on which framework is used in the project. I know I’ve used standalone classes as well previously but can’t remember exactly which.

  11. Andy says:

    PJ,

    Have you found a solution yet? I have the exact same problem.

    I am using the Mail() function and trying to send mail out from my code. For example order confirmation code, online lead etc.

    Typically some destinations work. Some don’t. Comcast emails addresses do not work. Yahoo almost always disappears. Gmail is ok.

    How to solve this. Adding my from address to the whitelist does not seem to solve the problem. Or will it?

    thanks

  12. wachiuri says:

    i have the same problem. i used the mail function on my computer that had XMail. so i sent to an account on my ;local computer. it sent the email just fine. the problem occurred when i try sending to other remote emails e.g yahoo and gmail.any body found the solution.

  13. vineet says:

    Hi,

    We are trying to use similar code mentioned above in our php to send mail. We have done appropriate settings as well in php.ini file. mail() function is returning ’1′ but its not sending any mail neither throwing any error.
    For your reference here is the code of php file

    ini file

    [mail function]
    ; For Win32 only.
    SMTP =
    smtp_port = 25

    ; For Win32 only.
    sendmail_from = xxx@yyy.com

    ; For Unix only. You may supply arguments as well (default: “sendmail -t -i”).
    sendmail_path = /usr/sbin/sendmail

    Can you please let me know what is the issue

  14. wdp says:

    Hi,
    I m trying to send email from a web page using PHP mail() function.

    example:
    mail($to, $subject, $message, $from);

    Mails are not received to its destination.

    Please let me know the solution…

    Thanks.

  15. Mahesh says:

    ini_set(“SMTP”, “mail.domain.com”);
    ini_set(“smtp_port”, 25);

    //ini_set(“sendmail_from”, “info@domain.com”);
    Hi sir

    I am using bellow code to send a mail, my client website is hosted on
    Windows IIS/6.0

    I am not able to send a mail using this code

    please give me a solution for this

    $mailTo = “name@hotmail.com”; // Recipient email id

    $subject = ‘Test mail’;
    $message = ‘Test mail’;

    $mailHeader = “Content-type: text/html; charset=iso-8859-1\r\n”;
    $mailHeader = $mailHeader . “From: info@domain.com\r\n”;
    $mailHeader = $mailHeader . “BCC: name@gmail.com\r\n”;

    if(mail($mailTo, $subject, $message, $mailHeader)) {
    echo “ok”;
    } else {
    echo “error”;
    }

    Thanks and regards

    Mahesh

  16. mailtester says:

    Hi all,
    I see there are recent comments, so here is a solution to the problem:
    1. You are using a web hosting service, that includes Linux e-mail service. Just create an e-mail account on your server:
    youremail@yourdomain.com

    2. in your php mailing script be sure to keep the following:
    $MailHeader = “From: Just created this account on WEB \n”;

    NB: this solves your problem about sending emails from the localhost. If you want your e-mails not to be handled as SPAM, simply add a next line to the mail header which contains your email as Reply-to.

    Best regards,
    John S.

  17. atsalycj says:

    Hi,

    i have been able to send email to my yahoo and gmail using the php mail script, but i don’t know why it doesn’t send to other domains like lycos.

    help anyone? :(

  18. Mario says:

    Thanks a lot. I have been looking for this very long. It works.

  19. Foodie2 says:

    Thank you, Danny, this is just what I needed.
    The mismatch between $SendEmail and $Headers “From” was the cause of endless hours of fruitless testing, trying to get mail to go to a Yahoo address. Note that AOL didn’t care.
    I have now forced a match by saying:
    ‘$SendEmail =”AnEmail@mydomain.co.uk”;
    $headers = “From:” . $SendEmail . “\r\n” .’

  20. ganesh says:

    hi ,
    i am not able to work in mail() function in php please give the solution detailed example.

    actually i am write given below
    mail($to,$subject,$message,) but it is not work .

  21. Niranjana says:

    Hi…

    I’m trying to receive form data through email. but its not workingout…

    can anyone pl help me…

    my php code is

    <?php
    if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "name@gmail.com";
    $email_subject = "feedback form";

    function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form your submitted. ";
    echo "These errors appear below.”;
    echo $error.”";
    echo “Please go back and fix these errors.”;
    die();
    }

    // validation expected data exists
    if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died(‘We are sorry, but there appears to be a problem with the form your submitted.’);
    }

    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required

    $error_message = “”;
    $email_exp = “^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$”;
    if(!eregi($email_exp,$email_from)) {
    $error_message .= ‘The Email Address you entered does not appear to be valid.’;
    }
    $string_exp = “^[a-z .'-]+$”;
    if(!eregi($string_exp,$first_name)) {
    $error_message .= ‘The First Name you entered does not appear to be valid.’;
    }
    if(!eregi($string_exp,$last_name)) {
    $error_message .= ‘The Last Name you entered does not appear to be valid.’;
    }
    if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.’;
    }
    $string_exp = “^[0-9 .-]+$”;
    if(!eregi($string_exp,$telephone)) {
    $error_message .= ‘The Telphone Number you entered does not appear to be valid.’;
    }
    if(strlen($error_message) > 0) {
    died($error_message);
    }
    $email_message = “Form details below.\n\n”;

    function clean_string($string) {
    $bad = array(“content-type”,”bcc:”,”to:”,”cc:”,”href”);
    return str_replace($bad,”",$string);
    }

    $email_message .= “First Name: “.clean_string($first_name).”\n”;
    $email_message .= “Last Name: “.clean_string($last_name).”\n”;
    $email_message .= “Email: “.clean_string($email_from).”\n”;
    $email_message .= “Telephone: “.clean_string($telephone).”\n”;
    $email_message .= “Comments: “.clean_string($comments).”\n”;

    // create email headers
    $headers = ‘From: ‘.$email_from.”\r\n”.
    ‘Reply-To: ‘.$email_from.”\r\n” .
    ‘X-Mailer: PHP/’ . phpversion();
    mail($email_to, $email_subject, $email_message, $headers);
    ?>

    Thank you for contacting us. We will be in touch with you very soon.

    Thanks

  22. sitta chaimongkol says:

    why mail function not send mail less than 3 charactor?

    example ab@sut.ac.th
    x@sut.ac.th

  23. Sandeep says:

    i have done settings in ppp.ini
    file like sendmail_path = /usr/sbin/sendmail
    but still e-mail does not send
    php script

    this php script runs without error but mail function returns
    nothing.

  24. Sam says:

    Hi, I’m having trouble with my PHP form, I believe it should work but sadly it isn’t and I have no idea why, can you help please.

  25. anand says:

    hi this is anand,i am having trouble when i am sending mail through php script,i am getting mail on my gmail account but not on yahoo .I don’t know why this problem get arises?
    Please help me out !
    Thanks in Advance.

  26. prabhat says:

    awesome its great

  27. Aiman says:

    Hi
    am using mail function to send out simple text emails but the page takes forever to reload(the mail is delivered successfully), is thee a way to make this work faster??

    Thanks

  28. Brijesh says:

    How can i configure my php.ini file so that i can send mail via the mail() function using gmail’s smtp connection

  29. Orion says:

    Heya,

    I hoping someone will be able to help me, as I’m at a loss as to what is causing the problem.
    Our website has a contact us form, with fields for name, email, kid name, kid ID, & message.
    When the form submits, the server side php code validates the form fields, & if all is good, uses the built in php mail() function to send 2 emails.
    Email 1 goes to an inbox on a hosted exchange server containing the values in the form fields.
    Email 2 goes to the person submitting the form saying thanks – we’ll get back to you shortly.
    For email 1, the From, Reply-To, & Return-Path headers are set to the email entered in the form, & the To param in the mail() function is the email address of the inbox of the hosted exchange server.
    For email 2, the From, Reply-To, & Return-Path headers are set to the email address of the inbox on the hosted exchange server, & the To param in the mail() function is the email address entered in the form.
    The website’s host has the MX, PTR, SPF, & TXT records set up properly to allow emails to be sent to & from the email address of the inbox of the hosted exchange server.
    The website’s host uses QMail as the SMTP service that actually sends the emails, & in all tests, QMail is receiving a success when sending both email 1 & 2. There is no error issued by the mail() function.

    Local tests were done with IE8, Chrome, & FF3.6.17. The code was not changed between tests showing this problem.
    In all test cases, email 2 (back to the person submitting the form) is sent just fine.
    Email 1, on the other hand, is only intermittently working. The general pattern is that the 1st time the contact form is used with each distinct email address in the form, the email is sent fine, & the headers & to are correct.
    The 2nd time the contact form is used with a previously used email address in the form, the To param is set to the email address in the form, the headers are all blank, & in spite of the To email address being incorrect, the email is not received.
    The website’s host’s support staff may have found another potential symptom, which is that after clearing cookies, all the email 2′s got through ok. However, the page does not use any cookies in relation to the form.
    Lastly, I tried again a while (30 mins?) after email 2′s weren’t getting through, then another try worked, after which the email 2′s screwed up as described above again.

    Is there a known bug with php’s mail() function along these lines? Is there a maximum frequency at which mail() can be used?
    I’m at a loss as to why the code sometimes works, & sometimes doesn’t. The website’s host’s staff are at a loss, as well.
    Trying to google this issue seems to turn up forums of people saying to use different modules (Swift Mailer, PHPMailer, Pear Mail, etc.), but as the website is live, I’m wary that rebuilding the automated emailing code will introduce errors beyond the one described above.

    - O8

  30. Orion says:

    given responses on other forums, Here’s the most pertinent code:

    function UserToSiteEmail( $name, $fromEmail, $message, $kidID, $kidName )
    {
    $subject = “Face of Kinder – contact us”;
    $headers = GetEmailHeaders($fromEmail);
    $imageFilename = constant(“URL_ROOT”).”/kidimages/”.$kid->ImageFilename;
    $profileUrl = constant(“URL_ROOT”).”/profile.php?k=”.$kid->KidID;
    $body = file_get_contents(“EmailTemplates/ContactUs.html”);
    $body = str_replace(“#FromName#”,$name,$body);
    $body = str_replace(“#FromEmail#”,$fromEmail,$body);
    $body = str_replace(“#KidName#”,$kidName,$body);
    $body = str_replace(“#KidID#”,$kidID,$body);
    $body = str_replace(“#Message#”,$message,$body);
    $body = str_replace(“#SiteRoot#”,constant(“URL_ROOT”),$body);
    return mail(constant(“FROM_EMAIL”),$subject,$body,$headers);
    }

    function GetEmailHeaders( $fromEmail )
    {
    $headers = “From: Face of Kinder ” . PHP_EOL;
    $headers .= “Reply-To: ” . $fromEmail . PHP_EOL;
    $headers .= “Return-Path: ” . $fromEmail . PHP_EOL;
    $headers .= ‘MIME-Version: 1.0′ . PHP_EOL;
    $headers .= ‘Content-type: text/html; charset=iso-8859-1′ . PHP_EOL;

    return $headers;
    }

    The UserToSiteEmail() funct uses the data from the contact us form, where the $fromEmail param is the email entered in the form. From what Rackspace could find in the QMail logs was that when the 2nd use of the same email in the contact us form gets submitted, the email in the form ends up in the To field, not in the headers, & the email inbox’s address didn’t show anywhere (not even the headers – i.e., it didn’t swap). This is even though the same code correctly put the form’s email into the header, & the email inbox’s address in the To field on the 1st submitting of the form (per browser).

    I can add the HTML side of the form if needed, but in terms of its process, after the form is submitted back to itself, after validating & emailing, the php redirects to a thanks page. I’m not certain how GET & POST variables would persist after the thank you page, as the only way back to the page is to click the link for the contact form again. To see the current process (without the problem – as it only seems to crop up when using the email inbox’s domain), here’s a link to a page with the contact us link in the footer: http://www.faceofkinder.com/home.php.

    - O8

  31. Orion says:

    lastly, here’s the QMail log indicating the problem…

    Jun 3 10:13:48 342812-web2 qmail-queue-handlers[1147]: Handlers Filter before-queue for qmail started …

    Jun 3 10:13:48 342812-web2 qmail-queue-handlers[1147]: from=

    Jun 3 10:13:48 342812-web2 qmail-queue-handlers[1147]: to=orionculver@b-street.co.uk

    Jun 3 10:13:48 342812-web2 qmail-queue-handlers[1147]: hook_dir = ‘/var/qmail//handlers/before-queue’

    Jun 3 10:13:48 342812-web2 qmail-queue-handlers[1147]: recipient[3] = ‘orionculver@b-street.co.uk’

    Jun 3 10:13:48 342812-web2 qmail-queue-handlers[1147]: handlers dir = ‘/var/qmail//handlers/before-queue/recipient/orionculver@b-street.co.uk’

    Jun 3 10:13:48 342812-web2 qmail-queue-handlers[1147]: starter: submitter[1148] exited normally

    Jun 3 10:13:48 342812-web2 qmail: 1307092428.798059 bounce msg 18353656 qp 1147

    Jun 3 10:13:48 342812-web2 qmail: 1307092428.798116 end msg 18353656

    Jun 3 10:13:48 342812-web2 qmail: 1307092428.798338 new msg 18353663

    Jun 3 10:13:48 342812-web2 qmail: 1307092428.798366 info msg 18353663: bytes 4902 from qp 1148 uid 2522

    Jun 3 10:13:48 342812-web2 qmail: 1307092428.800937 starting delivery 2481: msg 18353663 to remote orionculver@b-street.co.uk

    Jun 3 10:13:48 342812-web2 qmail: 1307092428.801071 status: local 0/10 remote 2/20

    Jun 3 10:13:48 342812-web2 qmail-remote-handlers[1149]: Handlers Filter before-remote for qmail started …

    Jun 3 10:13:48 342812-web2 qmail-remote-handlers[1149]: from=

    Jun 3 10:13:48 342812-web2 qmail-remote-handlers[1149]: to=orionculver@b-street.co.uk

    Jun 3 10:13:50 342812-web2 qmail: 1307092430.526801 delivery 2481: success: 98.129.184.131_accepted_message./Remote_host_said:_250_OK_BD/F0-16184-DC5A8ED4/

    Jun 3 10:13:50 342812-web2 qmail: 1307092430.526909 status: local 0/10 remote 1/20

    Jun 3 10:13:50 342812-web2 qmail: 1307092430.526938 end msg 18353663

    Jun 3 10:13:50 342812-web2 qmail: 1307092430.576988 delivery 2480: success: 98.129.184.131_accepted_message./Remote_host_said:_250_2.0.0_Ok:_queued_as_6D/F0-16184-DC5A8ED4/

  32. parul says:

    hi!
    i am using apache2.2 with php on port 80 on windows7
    php mail() function not able to send at my gmail account
    i am working on localhost

    please help me to get out this stuff
    thanks in advance

  33. Julio Osorio says:

    Nice post, that’s a really good tip I was looking for. Thanks a lot.

  34. parul says:

    hi!
    i am using apache2.2 with php on port 80 on windows7
    php mail() function not able to send at my gmail account
    i am working on localhost

    please help me to get out this stuff
    thanks in advance

  35. Gerbie Pejo says:

    can anyone help me with this, can’t send email using this php code…

    <?php
    error_reporting(0);
    // ' Send me an email' script

    if($_POST['submit'])

    {
    //get data from form
    $name = $_POST['name'];
    $message = $_POST['message'];

    if($name&&$message)
    { // existance check
    $namelen = 20;
    $messagelen = 300;
    if(strlen($name)<=$namelen&&strlen($message)<=$messagelen) // length check
    {
    // everything is ok!

    //set SMTP in php.ini

    ini_set("SMTP","mail.domain.com");
    ini_set("smtp_port",25);

    //set up the variables
    $to = "gerbiepejo@yahoo.com";
    $subject = "Email from Clarissa Jade Village Resort";
    $header = "From: ClarissaJade@yahoo.com";

    $body = "This is an email from $name\n\n$message";
    mail($to, $subject, $body, $header);

    die();
    }

    else
    die("Max length for name is $namelen, and max length for message is $messagelen!");
    }
    else
    die("You must enter your name and mesage”);
    }

    ?>

    Name:
    Message:

    thanks in advance!

  36. Hamad says:

    Struggled with this issue for a while!

    Thank you for sharing the solution.

  37. scarpe hogan says:

    having the same problem

  38. Danne says:

    I have a problem with my PHP Mail as well. It stops working from time to time without me even touching the code. I have a script wich checks if required forms are empty. This script works. But if I fill in all the required fields I should get a text wich sais “Your mail was successfully sent” but I dont. But if I just save and upload a identical file that already is on the server it starts working after a while. It’s often under the night it stops working. Can it be the server thats causing trouble or is it my code that I posted below?

    <?php

    if(isset($_POST['submit'])){

    $namn = strip_tags($_POST['namn']);
    $foretag = strip_tags($_POST['foretag']);
    $adress = strip_tags($_POST['adress']);
    $postnr = strip_tags($_POST['postnr']);
    $ort = strip_tags($_POST['ort']);
    $telefon = strip_tags($_POST['telefon']);
    $epost = strip_tags($_POST['epost']);
    $meddelande = strip_tags($_POST['meddelande']);

    function check_required_fields($required_array){
    $field_errors = array();
    foreach($required_array as $fieldname){
    if ((!isset($_POST[$fieldname])) || (empty($_POST[$fieldname]))){
    if($_POST[$fieldname] != '0'){
    $field_errors[] = $fieldname;
    }
    }
    }
    return $field_errors;
    }

    $errors = array();
    $required_fields = array('namn', 'telefon', 'meddelande');
    $errors = array_merge($errors, check_required_fields($required_fields));

    if(empty($errors)){

    $meddelande=nl2br($meddelande);

    if(empty($foretag)){ $foretag='-'; }
    if(empty($adress)){ $adress='-'; }
    if(empty($postnr)){ $postnr='-'; }
    if(empty($ort)){ $ort='-'; }
    if(empty($epost)){ $epost='-'; }

    $body =
    "
    Namn: “. $namn .”
    Företag: “. $foretag .”
    Adress: “. $adress .”
    Postnr: “. $postnr .”
    Ort: “. $ort .”
    Telefon: “. $telefon .”
    E-post: “. $epost .”
    Meddelande: “. $meddelande
    ;

    $headers = “From: $namn \r\n”;
    $headers .= “Content-type: text/html; charset=utf-8\r\n”;
    $headers .= “X-Mailer: PHP v”.phpversion();

    $success = mail(‘info@allflytt.com’, ‘Meddelande’, $body, $headers);

    }

    }

    ?>

    <form method="post" action="”>

    <?php
    if(!empty($errors)){
    echo "De rödmarkerade fälten måste fyllas i.”;
    }
    ?>

    <?php
    if(empty($errors) && $success){
    echo "Tack för ditt meddelande! Vi kommer att besvara det inom kort.”;
    }
    ?>

    <?php if(!empty($errors)){if(in_array("namn", $errors)){echo "”;}}?>Namn: *<?php if(!empty($errors)){if(in_array("namn", $errors)){echo "”;}} ?>

    <input type="text" name="namn" id="namn" class="text" tabindex="15" value="” />

    Företag:
    <input type="text" name="foretag" id="foretag" class="text" tabindex="20" value="” />

    Adress:
    <input type="text" name="adress" id="adress" class="text" tabindex="30" value="” />

    Postnummer:
    <input type="text" name="postnr" id="postnr" class="text_medium" tabindex="40" value="” />

    Ort:
    <input type="text" name="ort" id="ort" class="text" tabindex="50" value="” />

    <?php if(!empty($errors)){if(in_array("telefon", $errors)){echo "”;}}?>Telefon: *<?php if(!empty($errors)){if(in_array("telefon", $errors)){echo "”;}} ?>

    <input type="text" name="telefon" id="telefon" class="text" tabindex="60" value="” />

    E-post:
    <input type="text" name="epost" id="epost" class="text" tabindex="70" value="” />

    <?php if(!empty($errors)){if(in_array("meddelande", $errors)){echo "”;}}?>Meddelande: *<?php if(!empty($errors)){if(in_array("meddelande", $errors)){echo "”;}} ?>

  39. joe says:

    PEAR Mail works wonderfully. Here is my replacement function:

    /*
    must include PEAR packages Mail and mime. If these are not installed it will throw an error. Make sure your host has PEAR and these packages installed. If not you can easily install them.
    */
    include(“Mail.php”);
    include(“Mail/mime.php”);

    function pearmailer($from, $to, $subject, $plain_text, $html_text) {
    // headers
    $headers['From'] = $from;
    $headers['To'] = $to;
    $headers['Subject'] = $subject;

    // mime attachment
    $crlf = “\n”;
    $mime = new Mail_mime($crlf);
    $mime->setTXTBody($plain_text);
    $mime->setHTMLBody($html_text);
    $body = $mime->get();
    $hdrs = $mime->headers($headers);

    // send mail
    $mail =& Mail::factory(‘mail’, $params);
    $mail->send($to, $hdrs, $body);
    if(PEAR::isError($mail)) {
    return FALSE;
    } else {
    return TRUE;
    }
    }

  40. Chirag says:

    Anyone Help me ???
    I have problm in this code. I can not get email with this code. Please help me ….
    *******Html file :

    Untitled Document

    Name *

    Organization

    Email Address *

    Telephone Number *

    Comments *

    *******************php file

    Untitled Document

    <?php
    if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "technofirmsoftwares@gmail.com";
    $email_subject = "Mail from site";

    function died($error) {
    // your error code can go here
    echo "We are very sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.”;
    echo $error.”";
    echo “Please go back and fix these errors.”;
    die();
    }

    // validation expected data exists
    if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died(‘We are sorry, but there appears to be a problem with the form you submitted.’);
    }

    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required

    $error_message = “”;
    $email_exp = ‘/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/’;
    if(!preg_match($email_exp,$email_from)) {
    $error_message .= ‘The Email Address you entered does not appear to be valid.’;
    }
    $string_exp = “/^[A-Za-z .'-]+$/”;
    if(!preg_match($string_exp,$first_name)) {
    $error_message .= ‘The First Name you entered does not appear to be valid.’;
    }
    if(!preg_match($string_exp,$last_name)) {
    $error_message .= ‘The Last Name you entered does not appear to be valid.’;
    }
    if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.’;
    }
    if(strlen($error_message) > 0) {
    died($error_message);
    }
    $email_message = “Form details below.\n\n”;

    function clean_string($string) {
    $bad = array(“content-type”,”bcc:”,”to:”,”cc:”,”href”);
    return str_replace($bad,”",$string);
    }

    $email_message .= “First Name: “.clean_string($first_name).”\n”;
    $email_message .= “Last Name: “.clean_string($last_name).”\n”;
    $email_message .= “Email: “.clean_string($email_from).”\n”;
    $email_message .= “Telephone: “.clean_string($telephone).”\n”;
    $email_message .= “Comments: “.clean_string($comments).”\n”;

    // create email headers
    $headers = ‘From: ‘.$email_from.”\r\n”.
    ‘Reply-To: ‘.$email_from.”\r\n” .
    ‘X-Mailer: PHP/’ . phpversion();
    @mail($email_to, $email_subject, $email_message, $headers);
    ?>

    Thank you for contacting us. We will be in touch with you very soon.

    *****************************************
    Please help me as soon as possible.
    Thanks.

  41. peter says:

    Thanks for the quick solution.

    I do see one little mistake in your code:
    $headers = “From: $email_from”;

    should be:
    $headers = “From:” . $email_from;

  42. funkyville says:

    Danne, Thanks for posting this (in 2007). I spent hours trying to figure this out in 2012 until I found your info.

    FYI for anyone else having testing problems, here’s a simple script to use:

    <?php
    $to = "recipient@domain.com";
    $subject = "test";
    $body = "test";
    $email_from = "sender@domain2.com";
    ini_set("sendmail_from", $email_from);
    $headers = "From: $email_from";

    if (mail($to, $subject, $body, $headers)) {
    echo("Message successfully sent!”);
    } else {
    echo(“Message delivery failed…”);
    }
    ?>

  43. Lalit says:

    Hi Sir

    I have problem With this Code . I am not able to Receiving the Mail pls help..

    if(isset($_POST['submit'])){

    $name1=$_POST['name1'];
    $email1=$_POST['email1'];
    $phone1=$_POST['phone'];
    $project1=$_POST['project'];

    $to = “recipient@domain.com”;
    $subject = “Contact Details:”;
    $txt = “Name: $name1″.”\r\n”. “Email: $email1″.”\r\n”.”Phone: $phone1″.”\r\n”.”Project: $project1″;

    $headers = “From: $email1″ . “\r\n”;
    mail($to,$subject,$txt,$headers);

  44. Abhi says:

    Hi,

    i have problem With this Code. I have Used PHP Mail Function. it Worked fine previously But Now Client Said I am Not able to Receiving the any Mail. I am trying to some else there n not getting Solution…pls Help..

  45. Prakash says:

    Hi guys,
    I used mail function in php along with postfix it works fine for the previous days for the last couple of days it wasn’t work,
    i am screwed up in to this instance can anyone help me to fix

    Thanks

  46. Nikhil says:

    When i send mails from php , the mail is sent but it takes around an hour to send emails..can somebody please help

  47. Rajender says:

    I am trying to use mail function in localhost in linux..here whats the problem is what ever may be the string provided as a TO address.. the function is executing but mail is not delivering even to the correct mail ids…
    Any Suggetions may be helpful..

  48. Mats says:

    Hi,

    I’m trying to use this code to send e-mail from our site.

    ini_set(“SMTP”,”smtprelay1.telia.com”);
    ini_set(“smtp_port”,”25″);
    // $SmtpUser=”username”;
    // $SmtpPass=”password”;

    $from = “info@rdit.se”;
    $from_name = “RDIT Golf AB”;
    $subject = “Contact Form”;
    int_set($from_name, $from);

    $to = $_POST['email'];

    // collect data
    $body = “”;
    foreach($_POST as $key => $val)
    {
    if($key != ‘captcha’)
    $body .= ucfirst($key).”: “.$val.”\r\n”;
    }

    // construct MIME PLAIN Email headers
    $header = “MIME-Version: 1.0\n”;
    $header .= “Content-type: text/plain; charset=utf-8\n”;
    $header .= “From: $from_name \r\nReply-To: $from_name \r\nReturn-Path: \r\n”;

    // send email

    if (mail($to, $subject, $body, $header)){

    }
    else{

    }

    ?>

    When I ‘use Html 5 Builder it works perfectly, but when I try and run it outside the H5B it doesn’t work

    please help

    regards

3 Pings/Trackbacks for "Problem sending mail with PHP mail function"
  1. [...] Problem sending mail with PHP mail function (tags: php mail) [...]

  2. [...] web hosting companies do not have the right configuration for php mail. There may not always be a simple solution, and this can be quite frustrating. But what [...]

  3. [...] al script y utilizando php moví el script al servidor 13 veces). Finalmente, como se explica aqui, hay que inicializar la dirección desde donde se envía el correo en forma explícita en php. La [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>