SendGrid provides an HTTP GET endpoint to retrieve email statics based on country and state or province.
package org.wesome.sendgrid.controller;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.time.LocalDate;
@RestController
public class SendGridController {
@Autowired
private SendGrid sendGrid;
@GetMapping
public ResponseEntity sendGridAPI() throws IOException {
Request request = new Request();
Response response;
try {
LocalDate end_date = LocalDate.now();
LocalDate start_date = end_date.minusDays(30);
request.setMethod(Method.GET);
request.setEndpoint("geo/stats");
request.addQueryParam("start_date", String.valueOf(start_date));
request.addQueryParam("end_date", String.valueOf(end_date));
request.addQueryParam("country", "US");
request.addQueryParam("aggregated_by", "day");
request.addQueryParam("limit", "1");
request.addQueryParam("offset", "1");
response = sendGrid.api(request);
System.out.println("Headers := \n" + response.getHeaders());
System.out.println("Body := \n" + response.getBody());
System.out.println("StatusCode := \n" + response.getStatusCode());
} catch (IOException ex) {
throw ex;
}
return new ResponseEntity(HttpStatus.valueOf(response.getStatusCode()).getReasonPhrase(), HttpStatus.valueOf(response.getStatusCode()));
}
}
plugins {
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'org.springframework.boot' version '2.5.5'
id 'java'
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
repositories {
mavenCentral()
}
dependencies {
implementation 'com.sendgrid:sendgrid-java:4.4.5'
implementation('org.springframework.boot:spring-boot-starter-web')
}
test {
useJUnitPlatform()
}
send.grid.api.key=Your SendGrid Api Key
curl --location --request GET 'localhost:8080/'