개발자/Sendgrid

[Sendgrid/intellij/JAVA] API_KEY 발급 + JAVA 메일 발송 401, 403 오류

퍼플벌룬 2021. 5. 17. 18:30

Sendgrid 메일을 JAVA에서 적용하는 경우,

401 오류 : The provided authorization grant is invalid, expired, or revoked 오류는,

{"errors":[{"message":"The provided authorization grant is invalid, expired, or revoked"
,"field":null,"help":null}]}
{Strict-Transport-Security=max-age=600; includeSubDomains
, Server=nginx, Access-Control-Allow-Origin=https://sendgrid.api-docs.io,
Access-Control-Allow-Methods=POST, Connection=keep-alive
, X-No-CORS-Reason=https://sendgrid.com/docs/Classroom/Basics/API/cors.html, 
Content-Length=116, Access-Control-Max-Age=600, Date=Mon, 17 May 2021 07:42:51 GMT
, Access-Control-Allow-Headers=Authorization, 
Content-Type, On-behalf-of, x-sg-elas-acl, Content-Type=application/json}

SendGrid sg = new SendGrid(System.getenv("[API_KEY]"));

로 제공된 부분에 System.getenv("[API_KEY]") 에서 null을 반환하여 오류가 발생합니다. 

System.getenv("") 구문을 제거 후 정상동작을 확인할 수 있습니다.

        Email from = new Email("[sendgrid에서 등록한, 검증된 보내는 사람 메일]");
		Email to = new Email("[받는사람메일]");
		String subject = "Sending with Twilio SendGrid is Fun";
		Content content = new Content("text/plain", "and easy to do anywhere, even with Java");

		Mail mail = new Mail(from, subject, to, content);
		SendGrid sg = new SendGrid("[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;
		}

 

 


 

403 오류의 경우, "[sendgrid에서 등록한, 검증된 보내는 사람 메일]" 이 일치하지 않아서 발생하는 오류입니다. 

{"errors":[{"message":"The from address does not match a verified Sender Identity. 
Mail cannot be sent until this error is resolved. 
Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements","field":"from","help":null}]}

관리 사이트 내에서 'https://app.sendgrid.com/settings/sender_auth' 로 접근하여 이메일을 등록해주고, 해당 메일로 전송된 인증 메일을 통해 검증을 완료한 후 from 메일에 작성하여 발송테스트를 진행하면 됩니다.

아래 이미지와 같이 검증된! 마크가 있어야 완료 상태입니다.

 

API KEY 발급은 https://app.sendgrid.com/settings/api_keys 페이지로 접근하여

 

우측 API 키 생성 클릭

키 이름을 설정해주고, 전체 엑세스 [Full Access] 를 선택 

Create & View 클릭 시 바로 API키가 생성되며 다시 확인할 수 없으므로 잘 저장해두셔야 합니다. 

이 API_KEY를 이용해 메일을 발송합니다.