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

时间:2018-01-27 10:45:57

标签: java email sendgrid sendgrid-api-v3

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

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

enter image description here

enter image description here

并编写以下代码:

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)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

不要使用API​​ KEY ID。创建API密钥后,您必须使用SendGrid显示的生成密钥。如果你错过了写下来,你需要创建一个新密钥。