Implement email preference center and unsubscribe handling
✓Works with OpenClaudeYou are an email compliance engineer. The user wants to implement a secure email preference center with unsubscribe handling that complies with CAN-SPAM and GDPR requirements.
What to check first
- Verify your email service provider (ESP) supports list-unsubscribe headers — check SendGrid, Mailgun, or AWS SES docs for their unsubscribe implementation
- Confirm you have a database schema with
email_preferencesandunsubscribe_tokenstables with indexedemailandtokencolumns - Check that your application has a route handler for GET requests to
/email/unsubscribeor similar endpoint
Steps
- Generate and store secure unsubscribe tokens using
crypto.randomBytes(32)with SHA-256 hashing, storing both token hash and plaintext token in the database with a 30-day expiration - Add the
List-Unsubscribeheader andList-Unsubscribe-Postheader to all transactional emails pointing to your unsubscribe endpoint with the token as a query parameter - Create a preference center route that validates the token, verifies it hasn't expired, and displays checkboxes for email categories (marketing, transactional, weekly digest, etc.)
- Implement a POST endpoint that updates the
email_preferencestable with boolean flags for each subscription type, marking the token as used - Add a one-click unsubscribe handler that accepts POST requests with the token and immediately sets
unsubscribe_datetimestamp without requiring additional user interaction - Query the
email_preferencestable in your email sending logic before adding recipients to campaigns — skip any withopted_out = trueorunsubscribe_date < NOW() - Log all unsubscribe and preference change events with timestamp, IP address, and user agent for audit compliance
- Set up a weekly cleanup job to delete expired tokens older than 30 days and archive preference history for GDPR retention policies
Code
const crypto = require('crypto');
const express = require('express');
const db = require('./database'); // Your database connection
const router = express.Router();
// Generate unsubscribe token
function generateUnsubscribeToken() {
const token = crypto.randomBytes(32).toString('hex');
const hash = crypto.createHash('sha256').update(token).digest('hex');
return { token, hash };
}
// POST endpoint to send email with unsubscribe link
router.post('/send-email', async (req, res) => {
const { recipient, subject, body } = req.body;
const { token, hash } = generateUnsubscribeToken();
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
// Store token in database
await db.query(
'INSERT INTO unsubscribe_tokens (email, token_hash, expires_at, used) VALUES ($1, $2, $
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Email Skills
Other Claude Code skills in the same category — free to download.
React Email
Build beautiful emails with React Email components
MJML Templates
Create responsive email templates with MJML
Email Preview
Set up email preview and testing in development
Transactional Email
Build transactional email system with Resend or SendGrid
Email Queue
Queue and batch email sending for reliability
Email Deliverability Audit
Audit your email setup (SPF, DKIM, DMARC, BIMI) to maximize inbox placement
Email Template Design
Build email templates that render correctly in Gmail, Outlook, and Apple Mail
Want a Email skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.