I try to send email via sendGrid.
I've created api key on site:
and wrote following code:
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;
}
I get following exception:
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)
What've done I wrong?
Don't use the API KEY ID. You will have to use the generated key which SendGrid displays once you create your API key. If you missed to write it down, you'll need to create a new key.