Skip to content

Instantly share code, notes, and snippets.

@bbugh
Created March 20, 2013 18:57
Show Gist options
  • Save bbugh/5207416 to your computer and use it in GitHub Desktop.
Save bbugh/5207416 to your computer and use it in GitHub Desktop.
Creating a valid email address from a name and email, using the Ruby Mail library. Used to prevent invalid headers.

If you are taking user input for name and email, then unless you very carefully validate or escape the name and email, you can end up with an invalid From header by simply concatenating strings. Here is a safe way:

require 'mail'
address = Mail::Address.new email # ex: "john@example.com"
address.display_name = name # ex: "John Doe"
# Set the From or Reply-To header to the following:
address.format # returns "John Doe <john@example.com>"

From http://stackoverflow.com/a/8106387

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment