无法通过 sengrid v3 api 发送电子邮件(java.io.IOException:请求返回状态代码 401)

Could not send email via sengrid v3 api (java.io.IOException: Request returned status Code 401)

我尝试通过 sendGrid 发送电子邮件。

我在网站上创建了 api 密钥:

并编写了以下代码:

Email fromEmail = new Email("test@example.com");
            subject = "Sending with SendGrid is Fun";
            Email toEmail = new Email("test@example.com");
            Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
            Mail mail = new Mail(fromEmail, subject, toEmail, content);

            SendGrid sg = new SendGrid("9Vh5Wz9CQryyXVhWMFFQSw");
            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;
            }

我得到以下异常:

java.io.IOException: Request returned status Code 401Body:{"errors":[{"message":"The provided authorization grant is invalid, expired, or revoked","field":null,"help":null}]}
    at com.sendgrid.Client.executeApiCall(Client.java:287)
    at com.sendgrid.Client.post(Client.java:192)
    at com.sendgrid.Client.api(Client.java:310)
    at com.sendgrid.SendGrid.makeCall(SendGrid.java:151)
    at com.sendgrid.SendGrid.api(SendGrid.java:173)
    at pack.shared.email.EmailMessage$EmailService.sendEmail(EmailMessage.java:387)

我做错了什么?

不要使用 API KEY ID。创建 API 密钥后,您将必须使用 SendGrid 显示的生成密钥。如果您没有记下来,您将需要创建一个新密钥。