Search code examples
phpwordpresssmswordpress-hook

How to send an email when publish posts?


I wanted to send a email when publish post and i don't wanted to use plugin. i add below code to functions.php of my theme folder ,but it doesn't send any email to me. it goes to else part.

 function dothisfunction() {
     $sent = wp_mail("[email protected]","sms test", "message");
     if($sent) {
         echo "sent";
     }else {
         echo "failed";
     }

 }
 add_action( 'publish_post', 'dothisfunction' );

Solution

  • You might have one of the following reasons why it is not being sent

    1) There might be PHPMailer Exception : wp_mail is getting failed So try debugging the error using the below code

    // show wp_mail() errors
    add_action( 'wp_mail_failed', 'onMailError', 10, 1 );
    function onMailError( $wp_error ) {
        echo "<pre>";
        print_r($wp_error);
        echo "</pre>";
    }
    

    2) Wordpress relies on the PHPMailer class to send email through PHP's mail function.

    Since PHP's mail function returns very little information after execution (only TRUE or FALSE), I suggest temporarily stripping down your function to a minimum in order to see if the wp_mail functions works.

    $mailResult = false;
    $mailResult = wp_mail( '[email protected]', 'test if mail works', 'hurray' );
    echo $mailResult;
    

    3) You might be having server problems because "Not received" does not mean the same as "not sent" and this is an important distinction in troubleshooting.

    If other email addresses are receiving, then it is likely that something is flagging your message at the receiving hosts that you listed.

    4) Not all wordpress/server configurations allow the default Wordpress wp_mail function to send out mail. Certainly when testing on a local(host) server, lots of ISP's block the default outgoing mail traffic. Sometimes the blocking goes on silently, so it looks like everything works, but mail never gets sent. What helps is to install the WP Mail SMTP plugin (or similar) so you can configure outgoing SMTP servers (with or without authentication).

    5) There is a possibility that your email is being marked as spam, or it's simply your email provider is not allowing it to reach your inbox.

    Do you have SPF records setup? If you are sending an email from your website, and have the from header set as @gmail.com or @hotmail.com, this will surely not arrive in your inbox as the email is not originating from the gmail or hotmail servers, it's coming from yours, so it think's you are trying some phishing attack.

    So you should also check your spam/trash folders for interception.

    NOTE : There are many links related to this issue which you can go for but the ultimate favorite for everybody is to use WORDPRESS MAIL SMTP PLUGIN which i mentioned in point 4 and that resolves the issue for more than 95% of people.