Send Emails

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.

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.

Email Headers

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.

Example

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 “afterhoursprogramming@gmail.com”.

HTML Emails

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.

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.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *