πŸ‘¨πŸΌβ€πŸ’» Part 8: Sending an email

In PHP, one of the essential features is sending emails using the built-in mail() function. This function allows PHP scripts to send emails directly from a web server, making it useful for user notifications, password recovery, and contact forms.

The mail function is used for example in WordPress built-in forms.

Understanding the PHP mail function

The PHP mail() function enables email sending with a simple syntax:

mail(to, subject, message, headers, parameters);

Parameters explained:

  • to – The recipient’s email address.
  • subject – The email subject line.
  • message – The body of the email.
  • headers – Additional headers such as From, Reply-To, and Content-Type.
  • parameters – Optional additional parameters (e.g., setting a return path).

Creating a simple custom mail function

Here is a basic example of a custom PHP function to send an email:

$headers = "From: info@webster.ee\r\n";
$headers .= "Reply-To: your@email.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$to = "your@email.com";
$subject = "Welcome to Our Website";

$message = "Hello,<br>"; 
$message .= "welcome to our platform! We are excited to have you on board.<br><br>";
$message .= "Best regards, <br>";
$message .= "The Team MSG";

mail($to, $subject, $message, $headers);

Independent exercise

This exercise will help you understand the PHP mail() function, email headers, and proper message formatting using string extension syntax.
Write a PHP file to send an email using the mail() function.
Use previously-learned if-statement as well.

  • Use parameters for recipient, subject, and message.
  • Write a custom message
  • Include headers specifying From and Reply-To fields.
  • Test the function by sending a sample email to yourself.

Exercise #2

We want to debug our mail, but don’t want to send an email physically every time we reload the page.
So let’s only send an email out once certain condition is met. Let’s define a variable, which if equals “1”, we will debug our program.

  • Define a variable $testing = 1;
  • Write an if-statement, so that the mail() function would only be called, if $testing is 1.
  • Else just echo the message.

Scroll to Top