What Sender Policy Framework (SPF) means for your contact forms

Contact us forms on websites allow the user to fill in the form, and the contents are emailed back to the site owner. I often see people put the address the user gives as the “From” field in the email – here is why you shouldn’t do that.

So you run your blog on myblog.com, a little dinky server somewhere. It has a contact form and user@gmail.com comes along to send you a message. They fill out the form and press submit, and your server at myblog.com puts together an email message and sends it to you at me@myemail.com.

However, the operators of myemail.com have had enough of spam and are fighting back. One way is by using data from Sender Policy Framework records. This is a system where by the owners of a domain can specify which servers are allowed to send email for it. It is designed to prevent spoofing, where an email claims to come from a user but doesn’t really. Here’s what happens.

The server at myemail.com gets the email that claims to come from user@gmail.com. They look up the SPF records for gmail.com

james@ubuntu:~$ dig gmail.com TXT
....
gmail.com.    300    IN    TXT    
      "v=spf1 ip4:216.239.32.0/19 ip4:64.233.160.0/19"
....

We can see that Google has specified a list of IP blocks that are allowed to send email. At this point myemail.com notices that the email apparently from user@gmail.com really comes from myblog.com, a dinky little server that is not in one of those IP blocks. Having determined it to be a spoof email, it marks it as spam and you never see the message. Meanwhile, the user who sent the message gets disillusioned by your lack of response and never visits your site again.

So what do you do about it? Simple: don’t put the email address the user supplies as the “From” address. The “From” address should be an email address on the server, such as “blog@myblog.com”. What you can do is set the users email address as the “Reply-To” header (after carefully checking it is actually a email address to avoid header injection attacks) so that when you press reply in your email client the reply automatically goes to them and not blog@myblog.com.

I sat down to write this after seeing this mistake many times, including in a WordPress plugin with almost 10,000 downloads. My patch for the plugin is: patch.replyto, there is a discussion thread for it here.

ps. I’ve simplified the actual SPF record from Google for a simpler example.