How to send an email in PHP

Artboard 1.png

I was recently asked about sending an email via a PHP script. There are various ways to do this including third party plugins, scripts, or even just some basic PHP code.

In this article, I will just consider the basic PHP code required.

The code is fairly straightforward:

LINE 2: the address of the recipient

LINE 3: the subject of the email

LINE 4: the body of the email message

LINES 5 to 6: optional headers. Note that a ‘from’ email address is required but this could be set in your php,ini file. Note also that you will need to add CRLF (carriage return line feed) at the end of each header

LINE 8: actions the sending of the email using the PHP mail() function with the required parameters

That’s it.

I only tend to use this for internal testing or for picking up server errors when running scripts.