Send email with PHP

To send email with PHP the simplest thing is to use mail() function that the language offers us. This mail() function relies on the sendmail program to send emails. Sendmail usually comes configured with all PHP server installations.

In case you do not have it installed, I recommend that you take a look at the email configuration in PHP.

Let’s see what our PHP code would be like. We can verify that to send email with PHP very few lines are needed.

The first thing we have to do is define two variables that contain the message title and the message itself.

$titulo = 'Sending email from PHP';
$message = 'This is the first email I have sent from PHP';

Within the message we can include line breaks using the escaped characters ‘rn’:

$message = 'This is the first emailrnthat I have sent from PHP';

The next thing will be to define another variable with the email of the person to whom we sent the message:

$para = '[email protected]';

We will only have to invoke the mail() function to be able to send mail with PHP. To this function we will pass as parameters the variables $para, $title and $message in that order.

$sent = mail($to, $title, $message);

if ($sent)
  echo 'Email sent successfully';
else
  echo 'Error sending email';

The mail() function returns true if the message could be processed and false otherwise. That is why a simple validation can help us inform the user.

With this we will be able to send email with PHP. But there is a small detail that we have to emphasize. And the user that we have configured by default in the email sending program will appear to our recipient as the origin of the message. If you use a server, it is likely that it is a different user than yours.

So we are going to define a fourth variable that will be the origin. To do this we must put it in the header of the message.

$headers = 'From: My Name';

We will also pass this parameter to the mail() function.

$sent = mail($to, $title, $message, $headers);

Thus, with these few lines we will have managed to send email with PHP.

Leave a Comment