发送网格:"The provided authorization grant is invalid, expired, or revoked"

SendGrid: "The provided authorization grant is invalid, expired, or revoked"

我正在设置一个应用程序来向客户发送电子邮件。我正在使用 Java 和 SendGrid 创建此应用程序,但我遇到了 SendGrid 授权问题

我遇到错误:

java.io.IOException:请求返回状态码401Body:{"errors":[{"message":"The provided authorization grant is invalid, expired, or revoked","field":null,"help":空}]}

通读其他一些有类似问题的帖子,大多数问题似乎都得到了解决,因为人们使用的是 API 密钥 ID 而不是 API 密钥。我已经检查以确保我使用的是完整密钥,所以我认为这不是问题所在。

我也曾尝试创建一个新的 API 密钥,但这只是给出了同样的问题。最后,我尝试使用 Postman 进行类似的调用,并且使用相同的 API 键可以正常工作。

这是我用来发送电子邮件的主要 class。


import com.sendgrid.*;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;

import java.io.IOException;

public class SendEmail {

    public static void main(String[] args) throws IOException{
        Email from = new Email("FROM_EMAIL");
        String subject = "Sending with Twilio(?) is fun";
        Email to = new Email("TO_EMAIL");
        Content content = new Content("text/plain", "and easy to to anywhere, even with Java");
        Mail mail = new Mail(from, subject, to, content);

        SendGrid sg = new SendGrid(System.getenv("API_KEY"));
        Request request = new Request();

        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw(ex);
        }

    }

然后我通过这个片段在我的主要class中调用这个class:


    try{
            SendEmail.main(email);
    } catch(IOException ex){
            System.out.println(ex);
    }

"email" 字符串只是一个占位符,否则我在调用 class 时会收到一条错误消息,提示我需要一个数组。 (不确定这是为什么,会不会是问题的根源?)

明显的敏感信息已被删除,这就是为什么有些字段会被删除的原因。

顺便说一句,我按照教程在这个github:

https://github.com/sendgrid/sendgrid-java

告诉我你的想法。 提前致谢!

抱歉。我不知道 "System.getenv" 会获取环境变量。我设置了环境变量,问题解决了。

我认为您的环境变量设置不正确。尝试在没有 "System.getenv" 的情况下执行程序,如下所示。

SendGrid sg = new SendGrid("YOUR_API_KEY");