PHP has a built-in mail() function to send emails.
How Does it Work?
It requires the following parameters:
mail($to, $subject, $message);
If the server can send the email message, then the function returns true. Otherwise, it returns false. Let’s break down the parameters.
- $to – AKA The Recipient(s), it can be a non-domain name email or valid address on your domain. Required.
- $subject – The subject line of the email. Required.
- $message – The body of the email. Required.
An optional headers parameter is also available.
mail($to, $subject, $message, $headers);
- $headers – Additional features like from, replyto, cc, bcc, etc. Optional.
If defining a from in the $headers parameter, the email address has to have the domain name as the location of the PHP script. For example, the email has to come from ‘From: email@example.com’. The reply-to parameter can be assigned to the user’s email as they entered on the website’s contact form. For example, ‘Reply-To: firstname.lastname@example.org’.
<?php $to = 'email@example.com'; $subject = 'PHP email test'; $message = 'This is a test of the PHP mail() function.'; $headers = 'From: firstname.lastname@example.org'; $mailSent = mail($to, $subject, $message, $headers); if ($mailSent) : echo 'Email has been sent'; exit; else : echo "Couldn't send email"; endif; ?>
Try out the script on your local development machine utilizing MailCatcher or on a live staging server.