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
Keith Stephens 18Keith Stephens 18 

Salesforce and send grid Unauthorized endpoint

Hello All,
I hope someone out here can help me, I am wanting to send emails out using sendgrid, I have created my sendgrid API Key, I have added the endpoint to SF remote settings "https://api.sendgrid.com/v3/mail/send".
And this works all fine in our sandbox, but now that it is in our production environment I seem to be getting an "16:46:10:021 EXCEPTION_THROWN [30]|System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://api.sendgrid.com/v3/mail/send".

I have verified my code in our sandbox and production environments are they are the same code.
Is there something else I might be missing?
Thanks for any help,
Keith.
GovindarajGovindaraj
Hi Keith,

Make sure that URL is setup as an active URL in the Remote Site Settings

Thanks,
Govindaraj.S
Raj VakatiRaj Vakati

You haven't configured the remote site setttings to make an API call 


Before any Visualforce page, Apex callout, or JavaScript code using XmlHttpRequest in an s-control or custom button can call an external site, that site must be registered in the Remote Site Settings page, or the call fails.



To access the page, from Setup, enter Remote Site Settings in the Quick Find box, then select Remote Site Settings. This page displays a list of any remote sites already registered and provides additional information about each site, including remote site name and URL.


To register a new site:
  1. Click New Remote Site.
  2. Enter a descriptive term for the Remote Site Name.
  3. Enter the URL for the remote site. (https://api.sendgrid.com/v3/mail/send)
  4. To allow access to the remote site regardless of whether the user’s connection is over HTTP or HTTPS, select the Disable Protocol Security checkbox. When selected, Salesforce can pass data from an HTTPS session to an HTTP session, and vice versa. Only select this checkbox if you understand the security implications.
  5. Optionally, enter a description of the site.
  6. Click Save to finish, or click Save & New to save your work and begin registering an additional site.

 
Keith Stephens 18Keith Stephens 18
Yes the active box is checked, I have verified everything with our sand box.  Our sandbox is working but not production.
Thanks thou
Keith.
Keith Stephens 18Keith Stephens 18
Yes, I have done all of that and verified it's is set up just like we have in our sandbox, which is working.
User-added image
GovindarajGovindaraj
Keith, Can you post the callout code here ?
Keith Stephens 18Keith Stephens 18
public class EmailHelper { 
    @Future(callout=true)
    public static void sendEmail(String recipient, String candidate, String emailBodyText, String emailSubject) {
       
      
        try
        {
            //New instance of a single email message 
            //Messaging.SingleEmailMessage mail = 
            //    new Messaging.SingleEmailMessage(); 

            String body = emailBodyText;
           // recipient = 'kstephens@glofin.com';

            String[] tmpArrBody = Body.split('\n');
           // System.debug(tmpArrBody);           

            //String tmpSetBody = '{\"personalizations\":[{\"to\":[{\"email\":\"'+recipient+'\",\"name\":\"'+recipient+'\"}],\"subject\":\"TestTestTest '+emailSubject + ' ' + candidate+'\"}],\"from\":{\"email\":\"support@email.com\",\"name\":\"Support\"},\"reply_to\":{\"email\":\"support@email.com\",\"name\":\"support\"},\"content\":[{\"type\":\"text/plain\",\"value\":\"'+ JSON.serialize(body.replaceAll('\n', '\\n'))+'\"}]}';
            String tmpSetBody = '{\"personalizations\":[{\"to\":[{\"email\":\"'+recipient+'\",\"name\":\"'+recipient+'\"}],\"subject\":\"'+emailSubject + ' ' + candidate+'\"}],\"from\":{\"email\":\"rxcard@medchex.org\",\"name\":\"Support\"},\"reply_to\":{\"email\":\"rxcard@medchex.org\",\"name\":\"support\"},\"content\":[{\"type\":\"text/plain\",\"value\":\"'+ tmpArrBody +'\"}]}';

            //System.debug('tmpSetBody Before= '+tmpSetBody);
            HttpRequest req = new HttpRequest();
            Http http = new Http();            

            req.setEndpoint('https://api.sendgrid.com/v3/mail/send');
            req.setMethod('POST');
            req.setHeader('Content-Type', 'application/json');
            req.setHeader('authorization', 'Bearer MY_SENDGRID_APIKEY');    //This is sendgrids api key
            //New Key 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
            req.setBody(tmpSetBody);
            httpResponse response = http.send(req);
            String body2 = response.getBody();
                
            //system.debug('Our response: ' + body2);


                //// Who you are sending the email to 
                //// mail.setTargetObjectId(recipient); 
                //List<String> sendTo = new List<String>();          
                //sendTo.add(recipient);
                //mail.setToAddresses(sendTo);
                
                //String plainBody = '';
                //plainBody = emailBodyText;
                //mail.setPlainTextBody(plainBody);
                //mail.setSubject(emailSubject + ' ' + candidate);      

                //mail.setBccSender(false); 
                //mail.setUseSignature(false); 
                //mail.setReplyTo(recipient);    
                //mail.setSenderDisplayName(emailSubject);
                //mail.setSaveAsActivity(false);  
                
                ////mail.setWhatId(candidate); 
                // Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
                System.debug('Email Sent');
        }
        catch(Exception e)
        {
            System.debug('ERROR: EmailHelper.sendEmail ' + e);
        }         
 
    }   

}

 
Raj VakatiRaj Vakati
Can you change your req object like this and try

Refer this link 

https://github.com/sendgrid/sendgrid-apex/blob/master/src/classes/SendGrid.cls
 
HttpRequest req = new HttpRequest();
            Http http = new Http();            

            req.setEndpoint('https://api.sendgrid.com/v3/mail/send');
            req.setMethod('POST');
 
 
     req.setHeader('Content-Type','application/x-www-form-urlencoded');
     
    req.setHeader('Content-Length',String.valueof(tmpSetBody.length()));

	
	
            
            req.setHeader('authorization', 'Bearer MY_SENDGRID_APIKEY');    //This is sendgrids api key
            //New Key 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
            req.setBody(tmpSetBody);
            httpResponse response = http.send(req);
            String body2 = response.getBody();

 
GovindarajGovindaraj
Are you sure about the authorization ?

I could see in your code as, 
req.setHeader('authorization', 'Bearer MY_SENDGRID_APIKEY');
What is 'MY_SENDGRID_APIKEY' here ?

That should be something like below,
request.setHeader('Authorization', 'Bearer ' + <Token>);
Keith Stephens 18Keith Stephens 18
Thanks everyone for all the help, but actually we deleted our sendgrid key and created a new one, and we also had to white list sendgrids IP address. 
That resolved my issue.
Radhika Pawar 12Radhika Pawar 12
Hi All, Could you please guide me for Status=Forbidden, StatusCode=403 error. followed the same steps as per the above comments.