Sending emails in PHP is extremely easy. Before we get to sending emails, let’s think about why we might want to send an email in the first place. A simple contact form obviously requires an email to be sent. After a user creates an account, we probably want to send them an email so they can confirm their email address. There are many other uses of sending emails, but I don’t want you using email for the wrong purposes. Sometimes, you will see emails being awkwardly used for data storage rather than be alerts or some type of communication. Ultimately, a database is clearly a better way to do data storage and emails are great for communication.
Sending an Email
Now that we know why we might want to send emails, let’s start sending some. You might notice that sending emails is disabled in the PHP Notepad. Well, that is so spammers don’t use AfterHoursProgramming.com to send their junk mail. Anyways, let’s see an example.
Like I said, sending emails is easy with the mail(). All you need to provide is what email address you are sending the email to, the subject, and the message.
Sometimes, we want to send more than just the subject and message to someone. Maybe we want to provide a return address or send an HTML email. Well, these extra parameters all go in the email header. First, let’s just try to setting the return address.
So, all we did was to add another variable, $headers, to our mail function. The new variable joined two strings of text. First, we set who the email is from and then set the “Reply-To” to another email address. So, this email will say that it is from “AfterHoursProgramming.com”, but when you reply to the email, your response will go to “[email protected]”.
Sending HTML emails in PHP is pretty simple as well. We need to add a few more lines to our $headers variable and edit our message. Let’s take a look at an example.
After we set MIME type, Content Type, and the charset, PHP will just add these into the email header. Whenever an email service receives the email, it will check these parameters in the header and display the email as HTML. Don’t forget that you can use the style attribute to format your HTML email.