PHP Mail()
I’ve been doing a lot this week with PHP’s built in mail function. One of the projects i’m working on will require automated emails to be sent at regular intervals, so i’ve been weighing up the best way to achieve this.
First things is first, i needed to enable the PHP mail options within the PHP.ini file.
We are looking for the “[mail function]” section of the ini file. This is nice an easy to set up, you just need to enter a couple of lines to reflect the location of your mail server and the sender address that PHP will use.
[mail function]
; For Win32 only.
SMTP = email.domain.co.uk
smtp_port = 25
; For Win32 only.
sendmail_from = auto@domain.co.uk
; For Unix only. You may supply arguments as well (default: “sendmail -t -i”).
;sendmail_path =
; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =
Once these Lines have been added then a server restart is required for the changes to take effect.
Once rebooted we can write a simple page to test the configuration.
<?php
$to = "test@domain.co.uk";
$subject = "a test email";
$body = "this is a test email";
if (mail($to, $subject, $body)) {
echo("Message successfully sent!");
} else {
echo("Message delivery failed...");
}
?>
Put this somewhere on an accessible page and navigate to it in a browser. If all has been successful you should see a page simply saying “Message successfully sent” and await the arrival of your email.
There are many different things you can do with PHP mail. A quick search will help you find out how to make html messages and add elements such as a from address.
I said i wanted to send automated emails, so lets have a quick look at that. I very quickly found a simple solution, though im pretty certain it isnt the best way to do it - I shall investigate more in the coming week.
The way i found to do it (in windows) was to write a very simple one line batch file and schedule it as a system task to repeat daily.
My file is simply named “dailyemail.bat” and the content of the file is
php c:\websites\project\dailyemail.php
This file needs to be scheduled on the webserver as the “php” operator is dependent on having php available. When i find a better way i’ll let you know.
Posted in How To, Today's Achievements