How To Send Email Using PHP

Posted by TotalDC

Since we are on a roll with PHP tutorials, I thought it would be about time to learn how you can send email using PHP because almost every website on the internet has a function to contact the website owner via email.

The PHP Mail() Function In PHP

As you already know sending email messages is very common for a website. For example sending a welcome email when a user creates an account on your website sending newsletters to your subscribers, or getting user feedback through a contact form, etc.

For this, you can use the built-in PHP function mail() function for creating and sending email messages to one or more recipients dynamically from your website. The basic syntax of this PHP mail function looks like this:

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

Here are the parameters for PHP mail function with explanations:

  • to – The recipient’s email address.
  • subject – Subject of the email to be sent. This parameter in the example the subject line cannot contain any newline character (\n).
  • message – Defines the message to be sent. Lines should not exceed 70 characters.
  • headers – This is used to add extra headers such as “From”, “Cc”, and “Bcc”.
  • parameters – Used to pass additional parameters.

Sending Plain Text Emails With PHP

The simplest way to send an email with PHP is to send a simple text email. In this example we first declare the variables, then pass these variables to the mail() function to be sent.

<?php
$to = 'randomemaile@email.com';
$subject = 'Hello';
$message = 'Hi Paul!'; 
$from = 'anotherrandomemail@email.com';
 
l
if(mail($to, $subject, $message)){
    print 'Your mail has been sent successfully.';
} else{
    print 'Unable to send email. Please try again.';
}
?>

Sending HTML Formatted Emails With PHP

When you send a text message using PHP, all the content will be treated as simple text. We are going to improve this and make the email into an HTML-formatted email.

To send an HTML email idea looks the same. But this time you need to provide additional headers as well as an HTML-formatted message.

<?php
$to = 'random@email.com';
$subject = 'Hello';
$from = 'random@email.com';
 

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 

$headers .= 'From: '.$from."\r\n".
    'Reply-To: '.$from."\r\n" .
    'X-Mailer: PHP/' . phpversion();
 

$message = '<html><body>';
$message .= '<p style="color:#00FF00;">Hello World!</p>';
$message .= '</body></html>';
 
// Sending email
if(mail($to, $subject, $message, $headers)){
    print 'Your mail has been sent successfully.';
} else{
    print 'Unable to send email. Please try again.';
}
?>

Looks simple right? I suggest you go and implement what you have learned on your website. Remember, practice makes perfect.