Sending emails using PHP

In this post, we are going to learn about sending emails using PHP. The PHP mail() function is used to send emails from the script. This function has three mandatory parameters and two optional parameters.

Syntax

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

Parameters

Parameter

Description

to

This field is mandatory. Specifies the address of the receiver or receivers.

subject

This field is required. You can specify the subject of the email here.

message

The message parameter is also required. The message to be sent is specified here.

headers

Headers is an optional parameter. This is used to add additional headers such as From, Cc, Bcc.

parameters

This is also an optional parameter. This parameter can be used to pass additional parameters to the sendmail program.

Things to remember

The subject should not contain any newline characters.

Each line in the message should be separated with a LF (\n) and the lines should not exceed 70 characters.

For Windows only – If a line in the message starts with a full stop, it will be removed. Replace the full stop with a double dot to solve this problem.

The headers (if specified) should be separated with a CRLF (\r\n).

There must be a from header when sending an email. You can set it in the headers parameter.

Replacing a dot with double dots (For Windows).

<?php$text = str_replace("\n.", "\n..", $text);?>

Return values

The PHP mail function returns TRUE if the mail was sent, else it will return FALSE.

Example – sending a simple mail

<?php $message = "This is the message"; $message = wordwrap($message, 70, "\r\n");//to be used if the line is longer than 70 characters. if(mail('someone@example.com', 'My Subject', $message)) { echo "Mail has been sent."; } else { echo "Mail not sent."; }?>//If this method does not work, try adding headers as shown in the next example.