function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Varsha D 9Varsha D 9 

When i try to expose my apex class to rest api service to send a mail ....i m getting the error as ""message": "Session expired or invalid", "errorCode": "INVALID_SESSION_ID".....i tried regenerating my token tats not working

This is my apex code for generating mail through rest api @RestResource(urlMapping='/Email_2/*')    

global class Email2 {
@HttpPost
    // Public method
    global static void sendMail(String address, String subject, String body) {
        // Create an email message object
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new List<String>{'varsha.rcr37@gmail.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('subject2');
        mail.setPlainTextBody('body2');
        // Pass this email message to the built-in sendEmail method 
        // of the Messaging class
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        
    }
User-added imagei tried regenerating my token tats not working for me .....Whether i need to insert some HEADER or just Authorization Oauth 2.0 is fine...
Thanks in Advance
 
SwethaSwetha (Salesforce Developers) 
HI Varsha,

Based on https://help.salesforce.com/articleView?id=000335524&type=1&mode=1 When "Lock sessions to the IP address from which they originated" is enabled, if an OAuth2 access token is used to perform a Salesforce REST API call, INVALID_SESSION_ID might be returned even if the token is obtained in the same Apex transaction.

Try relaxing the IP restrictions or use the continuous IP enforcement feature mentioned as part of fix for this scenario in the documentation.

Incase this still doesn't fix the issue, please share the request body you are passing so I can replicate the behaviour in my org to suggest better.

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you