Email Services : Apex Class to unsubscribe Email

Email Services : Apex Class to unsubscribe Email

In Continuation to the Previous Blog i have written Titled  ,

Email Services in Salesforce with a simple example (https://wordpress.com/post/teamforcesite.wordpress.com/566)

Here is a requirement which can apply to almost any usage of the email services feature of salesforce . The unsubscribe Email functionality , is the feature by code where you can give your users an option to unsubscribe to further marketing emails from this address , Or our salesforce org.

Companies that send marketing email to their customers and prospects need to provide a way to let the recipients unsubscribe.
The following is an example of how an email service can process unsubscribe requests.
The code searches the subject line of inbound email for the word “unsubscribe.”
If the word is found, the code finds all contacts and leads that match the From email address and sets theEmail Opt Out field (HasOptedOutOfEmail) to True.

Scenario  : Handle Unsubscribe Email

[sourcecode language=”java”]
Global class unsubscribe implements Messaging.inboundEmailHandler {
Global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
Messaging.InboundEnvelope env) {

// Create an inboundEmailResult object for returning
// the result of the email service.
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

// Create contact and lead lists to hold all the updated records.
Listlc = new List();
Listll = new List();

// Convert the subject line to lower case so the program can match on lower case.
String mySubject = email.subject.toLowerCase();
// The search string used in the subject line.
String s = ‘unsubscribe’;

// Check the variable to see if the word unsubscribe was found in the subject line.
Boolean unsubMe;
// Look for the word unsubcribe in the subject line.
// If it is found, return true; otherwise, return false.
unsubMe = mySubject.contains(s);

// If unsubscribe is found in the subject line, enter the IF statement.
if (unsubMe == true) {
try {
// Look up all contacts with a matching email address.
for (Contact c: [SELECT Id, Name, Email, HasOptedOutOfEmail
FROM Contact
WHERE Email = : env.fromAddress
AND hasOptedOutOfEmail = false
LIMIT 100
]) {
// Add all the matching contacts into the list.
c.hasOptedOutOfEmail = true;
lc.add(c);
}
// Update all of the contact records.
update lc;
} catch (Exception e) {
System.debug(‘Contact Issue: ‘ + e);
}
try {
// Look up all leads matching the email address.
for (Lead l: [SELECT Id, Name, Email, HasOptedOutOfEmail
FROM Lead
WHERE Email = : env.fromAddress
AND isConverted = false
AND hasOptedOutOfEmail = false
LIMIT 100
]) {
// Add all the leads to the list.
l.hasOptedOutOfEmail = true;
ll.add(l);
System.debug(‘Lead Object: ‘ + l);
}
// Update all lead records in the query.
update ll;
} catch (Exception e) {
System.debug(‘Lead Issue: ‘ + e);
}

System.debug(‘Found the unsubscribe word in the subject line.’);
} else {
System.debug(‘No Unsuscribe word found in the subject line.’);
}
// Return True and exit.
// True confirms program is complete and no emails
// should be sent to the sender of the unsubscribe request.
result.success = true;
return result;
}
}
[/sourcecode]

Create this class and assign it to the Email Service you have configured.
This will automatically receive the emails and on receiving an email
with subject ‘Unsubscribe’ will search for contacts and leads and
Check the ‘hasOptedOutOfEmail’ checkbox Field to be true.

Happy Coding!!!

Leave a Comment

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

Recent Posts

Salesforce for Free Zone Authorities_ Managing Multi-Entity Licensing & Member Services
Salesforce for Free Zone Authorities: Managing Multi-Entity Licensing & Member Services
Agentforce for SaaS Companies_ What Dreamforce 2026 Is Likely to Announce and How to Prepare
Agentforce for SaaS Companies: What Dreamforce 2026 Is Likely to Announce and How to Prepare
NanaWall - Agentforce_banner copy
From Searching to Selling: Transforming Relationship Selling with an AI-Powered Sales Co-worker
Emarald
From Static Reports to Real-Time Decisions: Transforming Sales Intelligence with Salesforce CRM Analytics
Salesforce Org Audit Checklist for Software Companies — Before Dreamforce 2026
What We Keep Running Into on Agentforce Projects - And Where the Real Wins Are Before Dreamforce 2026
Scroll to Top