Personal blog

Writing every week about programming, new technology and books.

PHP

Sending emails with mail() function in PHP

01-Apr-2020
Sending emails with mail() function in PHP

Introduction

Almost every website now days has the option of sending or receiving emails from users. If you want to do that in PHP using built-in mail() function this tutorial will be useful to you. There are also other alternatives to this that I am going to list at the end of this blog.

Mail() function

If you go to official PHP documentation you can see this: 

mail ( string $to , string $subject , string $message [, mixed $additional_headers [, string $additional_parameters ]] )

So what does this mean?

- $to is the email of a person you want to send an email to.

- $subjet is subject in email.

- $message is the message of the email.

The other two parameters are optional.

How to check if email function works?

To check if your email function worked all you need to do is to place it inside if statement.

Here is an example:

$m = mail(example@email.com, "This is email subject", "This is email message", "From: noreply @ company . com");
if($m){
   //Tell user email is successfully sent
}
else{
    //Tell user email is not successfully sent
}

Warning

- This function can take up to five minutes to send an email.

- In some cases, there is an even possibility of not sending emails at all, this depends if user has an email client on his device.

Alternatives to mail() function

- Good alternative is phpmailer  

 

Thank you for reading this article, hopefully, you learned something new.