Mail test

How to Debug and Fix PHP Mail in Localhost

Sending emails in your local environment using PHP’s mail() function should be straightforward. The function is 20-years-old and one of the most integral parts of any web application; email.

If you’re not familiar with mail() , it’s a single function that only requires three arguments—a recipient, subject, and message—to deliver an email via one line of code. Sounds simple, right?

Well, if you’ve actually tried to use the function in your local environment, you know firsthand that it’s not always that easy. You’re probably reading this tutorial because you’ve experienced the mail() function not working out of the box yourself. Maybe you’re even one of the 343K viewers of this unresolved, 5-year-old Stack Overflow ticket.

So why isn’t my PHP mail function sending any mail?

The truth is, there could be a number of reasons why your emails aren’t arriving in inboxes. However, I’ve found that most of those reasons are related to Postfix not being configured properly. Postfix is a fast, secure, open-source mail transfer agent that routes and delivers emails. Postfix follows the SMTP protocol and runs on virtually every Unix-like operating system, including macOS.

Читайте также:  Exception handling with error codes in java

Because of its wide adoption, Postfix actually comes pre-installed on most non-Windows based computers. So why isn’t your PHP mail function working? It’s most likely because Postfix isn’t configured.

How do you configure Postfix?

Our test to see if Postfix is configured correctly actually begins with testing to see if it’s installed. In your terminal, run the following command:

Any errors outputted during this time may provide some insight as to what’s not working. However, if you get a response that indicates it’s installed, move on to the next section. If it hasn’t been installed, check out the Postfix documentation or contact your host for installation instructions.

Postfix has some minimum requirements that must be met before emails will send correctly.

The first thing you need to do is modify your local Postfix configuration. You can load an editor directly from your terminal by running the following command:

Once open, you’re going to check to make sure that the following 4 variables are defined as follows:

mail_owner=_postfix setgid_group=_postdrop myhostname=localhost.localdomain compatibility_level = 2 

That’s it! Save these changes and restart Postfix using sudo postfix reload .

NOTE: In my experience, the most important of these variables is myhostname . Without this variable being set, your local environment cannot assign a default location to send the email from. This value can be a real domain or something arbitrary just as in the example above.

Testing Postfix and PHP mail()

To test that Postfix is working and subsequently PHP mail() , let’s create a simple script to run. In your favorite integrated development environment (IDE), create a file called mail.php and add the following code:

Be sure to replace the $to variable with your actual email address. In your terminal, run the program using the following command and check your email:

Additional Troubleshooting

If you’ve tested Postfix and your PHP mail() function still isn’t sending mail, here are a few other issues to consider:

  • Missing required parameters (Check the official PHP mail documentation to verify.)
  • Typos with your recipient email address
  • Needing to set up an SMTP relay (This guide can help you set up Postfix to use SendGrid as a relay host.)

Conclusion

Now that you have completed this tutorial, you have the knowledge of setting up Postfix, the inconsistencies of mail() , and how to write a simple email script to send a test email in PHP.

If by chance you are still running into issues, feel free to reach out.

Marcus Battle is Twilio’s PHP Developer of technical content where he prompts and rallies PHP developers to build the future of communications. He can be reached via:

  • Marcus Battle
  • Julie Griffin
  • About
  • Legal
  • Copyright © 2023 Twilio Inc.
  • All Rights Reserved.
  • Protected by reCAPTCHA – Privacy – Terms

Источник

How to Test and Fix the php mail() Function

The php mail() function allows you to send emails directly from a php script.
This tutorial shows you how to test if php mail is working correctly.

Test php mail() on your Web Server

1. Create a php test file using a text editor and save it e.g. as test.php:

$sender = ‘ someone@somedomain.tld ‘;
$recipient = ‘ you@yourdomain.tld’ ;

$subject = «php mail test»;
$message = «php test message»;
$headers = ‘From:’ . $sender;

if (mail($recipient, $subject, $message, $headers))
echo «Message accepted»;
>
else
echo «Error: Message not accepted»;
>
?>

2. Change the $sender and $recipient in the code.

3. Upload the php file to your webserver.

4. Open the uploaded php file in your browser to execute the php script.

5. The output show either «Message accepted» or «Error: Message not accepted».

chevron_right Message accepted:

Open your mail client to see if the message was delivered to the specified email address.
(also check your spam folder!)

If the message was delivered:

If the message was not delivered:

  • Some provider don’t allow external recipients when using php mail. Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server’s domain, for example if your server domain is www.yourdomain.tld then the recipient’s email should be someone@yourdomain.tld.
  • Upload the modified php file and retry.
  • If it’s still not working: change the sender ($sender) to a local email (use the same email as used for recipient).
  • Upload the modified php file and retry.
  • Contact your provider if it still does not work.
    Tell your provider that the standard php «mail()» function returns TRUE, but not mail will be sent.
    It’s recommended to include the used php test script to show your provider, that the problem is not caused by the php script used.

chevron_right Error: Message not accepted

php mail might not be enabled:

  • Login to your webserver configuration and check the php settings.
    Some php installations require that you setup a default sender in the php configuration first.

Some provider don’t allow external recipients when using php mail:

  • Change the recipient ($recipient) in the code to a local recipient. This means use an email address from the server’s domain, for example if your server domain is www.yourdomain.tld then the recipient’s email should be someone@yourdomain.tld.
  • Upload the modified php file and retry.
  • If it’s still not working: change the sender ($sender) to a local email (use the same email as used for recipient).
  • Upload the modified php file and retry.

If you have checked the php settings, tried a local recipient and it’s still not working:

  • Contact your provider if you are unable to enable php mail().
    Tell your provider that the standard php «mail()» function returns FALSE.
    It’s recommended to include the used php test script to show your provider, that the problem is not caused by the php script used.

Disclaimer: The information on this page is provided «as is» without warranty of any kind. Further, Arclab Software OHG does not warrant, guarantee, or make any representations regarding the use, or the results of use, in terms of correctness, accuracy, reliability, currentness, or otherwise. See: License Agreement

  • ©1997-2023 Arclab®. All other trademarks and brand names are the property of their respective owners.
  • info_outline
  • fingerprint Cookies & Privacy

Источник

Как проверить работу функции mail() php

Внимание! Не забудьте удалить созданный тестовый php файл сразу же после проверки, иначе этим могут воспользоваться злоумышленники и начать рассылать спам с вашего веб-сайта, что может привести к блокировке заказанных услуг.

Иногда бывают ситуации, когда не совсем очевидно, на сайте отправка писем настроена, но письма не доходят или не отправляются. В этой ситуации самое простое решение — проверить функцию mail() php, а работает ли она? Или же возможно ограничена отправка писем?

Для проверки работоспособности PHP-функции mail() нужно создавать тестовый PHP-файл (например, mailtest55.php) следующего содержания:

".$_POST['email'].".
"; >else< $message = "Failed sending message to ".$_POST['email'].".
"; > >else< if (isset($_POST['submit']))< $message = "No email address specified!
"; > > if (!empty($message))< $message .= "

n"; > ?>
e-mail ">
subject
message
 

Загрузите созданный файл в рабочую папку веб-сайта, доступную по HTTP-протоколу (там где располжен index.php index.html).

Запустите файл, набрав его адрес (URL) в адресной строке браузера, например: http://example.com/mailtest55.php

Введите в поля открывшейся страницы адрес электронной почты, тему и текст проверочного сообщения и нажмите на кнопку «send», чтобы отправить сообщение.

В случае успешной отправки на странице появится сообщение вида «Email has been sent to . ». В противном случае появится сообщение вида «Failed sending message to. ».

Источник

PHP check if mail() function is enabled on your server

To check if mail function is enabled on your apache server you can try one of the following:

Check your php.ini like this:

You should search for this in the list sendmail_path that has the default value / usr / sbin / sendmail — t — i

You can also try to manual set it to this value by changing the php.ini file. To do this go to / etc / php5 / apache2 / php . ini and uncomment the sendmail_path line like this

If it did not work for you, try to find out if the function exists in the first place.

And finally you can test what the php mail() function returns.

But more important than this is if the email arrives to your inbox (or Spam folder).

I have also find myself in need to check the mail function a WordPress platform. You can do this on WordPress by installing Check Email plugin. Although it has not been updated lately it still works and it does the job that it was installed for.

check mail

Like I said, a positive result does not mean that the email will be received. There are much more things to check here.

Hope this helped you. If not please let me know how you finally solve it.

Leave a Reply Cancel reply

Recent Posts

How to embed video into a website – Ultimate tutorial Embedding a video into HTML website seems an easy task, but there really are lots of aspects to. PrettyPhoto Minimal Theme – a pure CSS prettyPhoto simple theme I have recently used prettyPhoto for a project and I have to admit that it is a great tool to have. AJAX POST request: Invalid request (Malformed HTTP request) on console and net::ERR_EMPTY_RESPONSE on chrome dev tools When you encounter the error «Invalid request (Malformed HTTP request)» in the console and. Using preg_split() to explode() by multiple delimiters in PHP Just a quick note here. To [crayon-64c2129b03c19722275536-i/] a string using multiple delimiters. How to use PHP to insert content after or before HTML tag The problem is quite simple. you just want to count a specific tag on a page and insert some. Simple OAuth2 authorization code grant example using PHP and cURL The authorization code grant methods, should be very familiar if you’ve ever signed into an. Limit the number of keywords in WordPress tag cloud to control PageRank Did you know that the default wordpress tags, labels or keywords from the sidebar can have a huge. URL vs. URI vs. URN, What’s the difference / examples What is URI A URI identifies a resource either by location, or a name, or both. More often than. Build your own WordPress Twenty Sixteen Child Theme Child themes are very popular these days. We will create a simple child theme for the Twenty. Create a modal window using pure HTML5 and CSS3 In this tutorial we will create a modal window using only HTML5 and CSS3 properties. The techniques. Remove admin bar wordpress backend and frontend So, as mentioned above, supposedly the new Toolbar is meant to be impossible to remove. The reason. 7 years Google Adsense earnings statistics and 10.000$ barrier reached If you are on this page, there are lots of chances you have a Google Adsense account, you are. PHP logical operators true false The [crayon-64c2129b068eb921164433-i/] and [crayon-64c2129b068f1863620448-i/] logical operators.

Источник

Оцените статью