I need to test a function that uses PHP's mail()
How can I do this without uploading the script to a server and test it online? What's even more I am developing with no Internet connection at all. I am on Mac OSX running localhost from XAMPP开发者_StackOverflow中文版.You don't have to install an MTA on your computer to test PHP's mail()
function. On Unix based systems (Linux, *BSD, OS X, etc.) you can set sendmail_path
to something like tee mail.out > /dev/null
. This will put the emails (including the headers) in a file called mail.out
.
Here is an example of how it would work:
daniel@daniel-laptop:~$ cat | php -d sendmail_path='tee mail.out > /dev/null'
<?php
mail('test@example.com', 'the subject', 'the body');
?>
daniel@daniel-laptop:~$ cat mail.out
To: test@example.com
Subject: the subject
X-PHP-Originating-Script: 1000:-
the body
You can set sendmail_path
in your php.ini
file. If you want to append emails to the file instead of overwriting each time, you can use tee -a
instead of just tee
.
To test sending email from apache do the following
create a folder to store the email.
/home/username/Documents/TestEmails
Give permission to apache. From the Documents folder, run
sudo chgrp -R www-data TestEmails
Modify the php.ini file, mine is located at
/etc/php5/apache2/php.ini
set sendmail_path
sendmail_path ='cat > /home/username/Documents/TestEmails/mail.txt'
Restart apace2
sudo service apache2 restart
A nice and simple solution for testing:
http://blogs.bigfish.tv/adam/2009/12/03/setup-a-testing-mail-server-using-php-on-mac-os-x/
Updated link:
https://github.com/ifunk/smtp-catcher
Hmm. I haven't tried this, but in php.ini you can set "sendmail_path" ... so in theory you could write your own shell script that simply wrote the input into text files, and change your php.ini to use that? Then simply run tests and check text files!
If you're on Windows/using something like WAMP/UWAMP/XAMPP and need to test mail then Papercut is well worth a look:
https://github.com/ChangemakerStudios/Papercut
You can leave your SMTP settings in php.ini as the defaults (localhost/25) and it just works. It looks like an email client and shows all the parts of/details of a message in separate sections.
Setup a pop3 server in local Machine. Many available for free. and send mails within your local domain using sendmail.
By default its not required to set the sendmail path in Linux. at least I never needed it. just use the mail() function and hit mails on local domain
Building on the answer @Daniel-Egeberg provided, this is what worked for me on Ubuntu 18.04:
I opened /etc/php/7.2/apache2/php.ini and set:
sendmail_path='tee /path/to/file/mail.out'
restarted:
sudo service apache2 restart
then created /path/to/file/mail.out and changed permissions for it:
chmod 666 /path/to/file/mail.out
精彩评论