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 websites owner via email.

The PHP Mail() Function

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

For this you can use 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 function looks like this:

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

And here is parameters with explanations:

  • to – The recipient’s email address.
  • subject – Subject of the email to be sent. This parameter in 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”, “Bcc”.
  • parameters – Used to pass additional parameters.

Sending Plain Text Emails

The simples 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

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 a 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 sugest you go and implement what you have learned in your website. Remember, practice makes perfect.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: