Sending email messages are very common for a web application, for example, sending welcome email when a user create an account on your website, sending newsletters to your registered users, or getting user feedback or comment through website’s contact form, and so on.
You can use the PHP built-in mail()
function for creating and sending email messages to one or more recipients dynamically from your PHP application either in a plain-text form or formatted HTML.
The basic syntax of this function can be given with:
mail(to, subject, message, headers, parameters)
The simplest way to send an email with PHP is to send a text email. In the example below we first declare the variables — recipient’s email address, subject line and message body — then we pass these variables to the mail()
function to send the email.
<?php $to = 'maryjane@email.com'; $subject = 'Marriage Proposal'; $message = 'Hi Jane, will you marry me?'; $from = 'peterparker@email.com'; // Sending email if(mail($to, $subject, $message)){ echo 'Your mail has been sent successfully.'; } else{ echo '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’re going to improve that output, and make the email into a HTML-formatted email.
To send an HTML email, the process will be the same. However, this time we need to provide additional headers as well as an HTML formatted message.
<?php $to = 'maryjane@email.com'; $subject = 'Marriage Proposal'; $from = 'peterparker@email.com'; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Create email headers $headers .= 'From: '.$from."\r\n". 'Reply-To: '.$from."\r\n" . 'X-Mailer: PHP/' . phpversion(); // Compose a simple HTML email message $message = '<html><body>'; $message .= '<h1 style="color:#f40;">Hi Jane!</h1>'; $message .= '<p style="color:#080;font-size:18px;">Will you marry me?</p>'; $message .= '</body></html>'; // Sending email if(mail($to, $subject, $message, $headers)){ echo 'Your mail has been sent successfully.'; } else{ echo 'Unable to send email. Please try again.'; } ?>
Note that a per previous tutorials, be sure to use your own DkIT student email for the from address, and be aware that you can only email other users inside DkIT by default.
You can now pass data provided by the user on to the site owner via email.