PHP mail() is one of the useful functions you can use to send an email to one or more people. You can also use this function to send emails dynamically to people such as who submit a form or who contact you via website. Recently, I was creating a course Creating Social Network in PHP in which I used email verification for users who wanted to register on the social networking website. Since I wanted to send the email to the users in HTML format which look a lot better and professional rather than sending the plain-text email, so I did that and now I’ll exactly give you the code for sending PHP emails in HTML format.
The Simple Plain-Text Email in PHP
First of all, you should know about the basic email functionality in PHP, for example you want to send email to someone using PHP then you’ll have to use PHP mail function for it, and for that you need four parameters to be added in the email function something like this:
$to = “email@example.com”;
$subject = “Verify Your Email”;
$message = “This is a message for you!”;
$from = “firstname.lastname@example.org”;
The above four local variables hold some information and then we use the PHP mail() function to send the email, this email will only send plain data, I mean normal text, and you can’t send any HTML tags in this email, that will not work. But if you want to send a beautiful HTML & CSS formatted email then you do so. Carry on reading.
Sending PHP Email with HTML & CSS
Now here is the magic, you can use extra headers to send an email which contains HTML and CSS codes, and this will be actually applied on the page. Now below is the full code which you can straight take from here and can use in your projects, this will send the email to the user which is in the $to variable, and the email will be fully designed.
$to = “email@example.com;
$subject = “Verify your email address.”;
$message = ”
Hello <strong>John Doe</strong>
<h2>We are a company here in the USA</h2>
<marquee>We do business with clients</marquee>
<h3 style=’color:read;’>We welcome you to our website</h3>
// Always set content-type when sending HTML email
$headers = “MIME-Version: 1.0” . “\r\n”;
$headers .= “Content-type:text/html;charset=UTF-8” . “\r\n”;
$headers .= ‘From: <firstname.lastname@example.org>‘ . “\r\n”;
The above email is the perfect one with HTML and CSS Website tags, you can change it according to your own information. But the important part in above email syntax is the $headers variable in which we’ve defined the version and content type with character set. So now, this format will be treated as HTML email by the browser and email provider. You can change the from:<email@example.com> to your own email from which you want to send an email to someone.
If you have any questions about this tutorial or any other tutorial on this website then don’t hesitate to ask your question using below commenting form, we’ll be adding more useful tutorials on web development o this blog.