Advertisement
Creative Coding

Using WordPress for Web Application Development: Features: Email

by

One of the major components of every web application is its ability to send email.

Now this doesn't mean that each web application is its own mail client (though people do certainly create their own).

Instead, I mean that applications normally send emails when a user signs up, a user modifies their password, when something in the system changes, or - more generally speaking - whenever something occurs for which the site owners want to notify the users.

So far in this series, we've covered:

  • User management
  • Permissions
  • Session Management

The last article was arguably one of the most complicated that we'll cover; however, it's necessary for those of you looking to add more advanced functionality to your projects.

With that said, we'll take a break from some of the more complicated material and take a look and what WordPress has to offer as far as sending emails is concerned.


Understanding Email

Before we dive into what the WordPress API offers in the way of sending emails, customizing emails, and the like, it's important to understand a couple of things about email.

Namely, it's important to understand the components that go into creating an actual email - after all, it's more than just an address, subject, and content.

There are some technical nuances that are worth understanding before we go about constructing our own custom emails.

Headers

In short, email headers contain a minimum set of information including: from whom the email is being sent, and the addresses to which the email is being sent.

Typically, you're likely to see additional information included in the header. For example, this information may include a timestamp for when the email is sent.

When it comes to WordPress, the sender specified in the email header is always defined as the default sender in WordPress, unless otherwise specified.

For example, if you're looking to set the reply address as "donotreply@domain.com", then this is something you have to customize.

Additionally, it's usually a good idea to work with email headers in the form of an array so that you can easily construct, specify, and pass to addresses, carbon copy addresses, and blind carbon copy recipients.

MIME Type

When it comes to the format that emails follow, you're likely to see two forms:

  • Plain text
  • HTML

You're used to seeing HTML in most modern email clients; however, if you have a more simplistic client, you have it set to only display plain text, or you're reading email on a slightly older phone, then you'll be reading the content in plain text.

WordPress makes it possible to send emails in either plain text or HTML.

When we look at an example of how to programmatically send an email, we'll take a look at exactly how to do that. In short, there's a hook that makes it really easy - but we'll wait to see it in action until we cover the rest of the necessary parts of an email.

Attachments

As you know, attachments are practically any file that you've attached to an email and that you send to a recipient.

The thing is, there are some rules governing email - they aren't necessarily set by the software, though. Instead, servers, email clients, and other various rules restrict what we can receive in our inbox.

For example:

  • Some clients don't allow zip files or executable files to be sent
  • Many email services have a maximum file size that can be attached
  • Certain types of email may be flagged as spam based on their attachments (or their contents)

Regardless, that's beyond our control - we just need to know the limitations of who we're sending email to and make sure we stay within them.

To that end, creating attachments to send with WordPress emails is really easy.

Though attachments are obviously not required, you may want to attach a single file or even multiple files. In WordPress, this can be done with either a string or an array.

We won't take a look at exactly how to do that right now, but we will get to that momentarily when we look at an example of how to programmatically send an email.

To, Subject, and Message

At the most basic level, every email consists of a "To" email address, a "Subject", and a "Message".

In WordPress, these are really easy to set as well - simply provide strings for each and you're ready to go.

Of course, if you want to send an email to multiple people you can either iterate through a collection of addresses and send one email per user, or you can provide an array of recipients to the WordPress Mail API and it will dispatch the email to all of those who are included.

And remember: If you want to specify a different reply-to address, that goes in the headers that we covered earlier in the article.


Using the WordPress Email API

So with all of that said, we're ready to actually take a look at the WordPress Email API.

In short, all of the functionality is wrapped up in a function called wp_mail; however, there are a few hooks of which we need to be aware if we want to take full advantage of the application's offering.

The Required Hooks

Specifically, we're going to use the following hooks:

  • wp_mail_content_type allows us to define the MIME type of the email being sent
  • wp_mail_from is a filter that we can use to define the from address, rather than using the $headers array
  • wp_mail_from_name is a filter that we can use to define the person's from, rather than using the $headers array
  • wp_login is the hook that we'll use for demonstration such that we're sending emails to a person whenever a person logs into the WordPress dashboard

For the sake of completeness, I'll share the whole code below and then we'll walk through it.

The Source Code

<?php
function acme_email_individual( $input ) {

	/**
	 * Note: assume that $input has keys for 'email-address'.
	 */

	// Generate the password
	$password = wp_generate_password ( 12, false );

	// Email the user that they're profile was created
	$message = 'Hey There,';
	$message .= '<br /><br />';
	$message .= 'Your account has been created. Your login information is below:';
	$message .= '<br />';
	$message .= '<ul>';
		$message .= '<li>Username: ' . $input['email-address'] . '</li>';
		$message .= '<li>Password: ' . $password . '</li>';
	$message .= '</ul>';
	$message .= '<br />';
	$message .= 'You can login to the application <a href="' . get_bloginfo( 'siteurl' ) . '">here</a>.';

	add_filter( 'wp_mail_content_type', create_function( '', 'return "text/html";' ) );
	add_filter( 'wp_mail_from', 'acme_mail_from' );
	add_filter( 'wp_mail_from_name', 'acme_mail_from_name' );
	wp_mail( $input['email-address'], 'Your Acme Account Has Been Created!', $message, array() );

}

function acme_mail_from( $email ) {
	// NOTE: replace [at] with @. This was causing problems with the syntax highlighter.
	return 'donotreply[at]acme.com';
}

function acme_mail_from_name( $name ) {
	return 'The Acme Company';
}

If you've been following along with this article thus far, then none of this should be terribly surprising: After all, we're taking advantage of the hooks that WordPress provides, we're building strings to pass as function arguments, and then we're calling the wp_mail function.

Notice however, that we are passing an empty array as the $headers argument for this email. This is because we're using a custom filter to set the "From Name" and the "From Address" using a filter and a hooked function rather than an array.

This way isn't necessarily better than the alternative; however, it's meant to demonstrate that there are multiple ways to achieve the same result.


And Now, on to Data!

So this is yet another feature of WordPress that makes it really easy to include email functionality into your web application.

In fact, I think WordPress' eventing model makes it ridiculously easy to introduce email functionality for just about any scenario imaginable - if there's a hook available for it, an email can be sent.

With that said, it's time to turn our attention to one of the most common aspects of web application development: data management.

Specifically, we need to look at how information can be saved to the database and retrieved from the data, and how it can be done so safely and efficiently.

So starting in the next article, we'll do exactly that.

Related Posts
  • Code
    Creative Coding
    Using WordPress for Web Application Development: WP_User_QueryApplication foundation 400
    In this series, we've been taking a look at how WordPress can be used to development web applications much like a number of different frameworks and other tools that are available. Starting in the last article, we began looking at the different options that we have as it relates to querying the WordPress data. First, we reviewed WP_Query.Read More…
  • Code
    PHP
    Validation and Exception Handling: From the UI to the BackendProcedural to oop php retina preview
    Sooner or later in your programming career you will be faced with the dilemma of validation and exception handling. This was the case with me and my team also. A couple or so years ago we reached a point when we had to take architectural actions to accommodate all the exceptional cases our quite large software project needed to handle. Below is a list of practices we came to value and apply when it comes to validation and exception handling.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Code
    PHP
    Sending Emails With Laravel 4 & GmailLaravel 4 auth retina preview
    Sending emails is crucial for any web application. Usually, an email is sent to notify the user of some kind of activity that has taken place on the site, for example, such as when updates have been made or when new friends have been found. In this short tutorial, I'll show you how to send emails with Gmail quickly from within a Laravel sample application by extending the functionality that we built in my last tutorial, Authentication With Laravel 4.Read More…
  • Code
    Creative Coding
    Using WordPress For Web Application Development: Features: User ManagementApplication foundation 400
    Throughout this series, we've been taking a look at how WordPress can serve as a foundation for web application development. The thing is, up to this point, we haven't really taken a look at the features of WordPress that really contribute to building web applications. Instead, we've spent time looking at how WordPress serves as a foundation rather than a framework, and we've looked at how WordPress is organized in comparison to many of the modern frameworks that are available.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Understanding Events, Actions, and FiltersApplication foundation 400
    Throughout this series, we've been taking a look at how WordPress can be used for building web applications. Up to this point, we've established that WordPress is a foundation - rather than a framework - and we've talked a bit about how we need to avoid trying to shoehorn WordPress into another type of design pattern than that of its native type.Read More…