diff --git a/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java b/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java index 204b8fb..ed10cb7 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java +++ b/src/main/java/io/ljunggren/sendgrid/api/SendgridApi.java @@ -7,6 +7,7 @@ import io.ljunggren.sendgrid.api.model.Statistics; import io.ljunggren.sendgrid.api.service.Aggregation; import io.ljunggren.sendgrid.api.service.EmailService; +import io.ljunggren.sendgrid.api.service.SuppressionService; import io.ljunggren.sendgrid.api.service.UsageService; /** @@ -24,6 +25,7 @@ private final EmailService emailService; private final UsageService usageService; + private final SuppressionService suppressionService; /** * Create a new {@code SendgridApi} using the given API key. @@ -32,7 +34,7 @@ * @throws IllegalArgumentException if {@code apiKey} is null or blank */ public SendgridApi(String apiKey) { - this(new EmailService(apiKey), new UsageService(apiKey)); + this(new EmailService(apiKey), new UsageService(apiKey), new SuppressionService(apiKey)); } /** @@ -43,11 +45,24 @@ * @param usageService usage service */ SendgridApi(EmailService emailService, UsageService usageService) { + this(emailService, usageService, null); + } + + /** + * Package-private constructor primarily used by tests to + * inject mock services. + * + * @param emailService email service + * @param usageService usage service + * @param suppressionService unsubscribe group suppressions (may be null in tests that don't use it) + */ + SendgridApi(EmailService emailService, UsageService usageService, SuppressionService suppressionService) { if (emailService == null || usageService == null) { throw new IllegalArgumentException("emailService and usageService must not be null"); } this.emailService = emailService; this.usageService = usageService; + this.suppressionService = suppressionService; } /** @@ -77,6 +92,33 @@ } /** + * Send a SendGrid template email in an unsubscribe group: SendGrid adds the unsubscribe link and header, and + * skips people who unsubscribed from that group. + * + * @param templateId SendGrid template id + * @param from sender address + * @param to recipient address + * @param templateData substitution variables + * @param asmGroupId unsubscribe group id; null for none + * @throws SendgridException if the email cannot be sent + */ + public void sendTemplateEmail(String templateId, String from, String to, Map templateData, + Integer asmGroupId) throws SendgridException { + emailService.sendTemplateEmail(templateId, from, to, templateData, asmGroupId); + } + + /** + * Take an address off an unsubscribe group's suppression list (it opted back in somewhere else). + * + * @param groupId unsubscribe group id + * @param email the address + * @throws SendgridException on error + */ + public void deleteGroupSuppression(int groupId, String email) throws SendgridException { + suppressionService.deleteGroupSuppression(groupId, email); + } + + /** * @return statistics for today only * @throws SendgridException on error */ diff --git a/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java b/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java index ed3234e..ecd67f8 100644 --- a/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java +++ b/src/main/java/io/ljunggren/sendgrid/api/service/EmailService.java @@ -9,6 +9,7 @@ import com.sendgrid.Response; import com.sendgrid.SendGrid; import com.sendgrid.helpers.mail.Mail; +import com.sendgrid.helpers.mail.objects.ASM; import com.sendgrid.helpers.mail.objects.Content; import com.sendgrid.helpers.mail.objects.Email; import com.sendgrid.helpers.mail.objects.Personalization; @@ -72,6 +73,23 @@ * @throws SendgridException if the email cannot be sent */ public void sendTemplateEmail(String templateId, String from, String to, Map templateData) throws SendgridException { + sendTemplateEmail(templateId, from, to, templateData, null); + } + + /** + * Send a templated email in an unsubscribe group (SendGrid's "Advanced Suppression Manager"). SendGrid then adds + * its List-Unsubscribe header, fills the template's {@code {{{unsubscribe}}}} and + * {@code {{{unsubscribe_preferences}}}} links, and skips recipients who unsubscribed from that group. + * + * @param templateId SendGrid template id (must not be null or blank) + * @param from sender address (must not be null or blank) + * @param to recipient address (must not be null or blank) + * @param templateData substitution variables; may be null or empty + * @param asmGroupId unsubscribe group id; null for none (e.g. transactional email) + * @throws SendgridException if the email cannot be sent + */ + public void sendTemplateEmail(String templateId, String from, String to, Map templateData, + Integer asmGroupId) throws SendgridException { requireNonBlank(templateId, "templateId"); requireNonBlank(from, "from"); requireNonBlank(to, "to"); @@ -84,6 +102,12 @@ templateData.forEach(personalization::addDynamicTemplateData); } mail.addPersonalization(personalization); + if (asmGroupId != null) { + ASM asm = new ASM(); + asm.setGroupId(asmGroupId); + asm.setGroupsToDisplay(new int[] { asmGroupId }); + mail.setASM(asm); + } sendEmail(mail); } diff --git a/src/main/java/io/ljunggren/sendgrid/api/service/SuppressionService.java b/src/main/java/io/ljunggren/sendgrid/api/service/SuppressionService.java new file mode 100644 index 0000000..97d701e --- /dev/null +++ b/src/main/java/io/ljunggren/sendgrid/api/service/SuppressionService.java @@ -0,0 +1,66 @@ +package io.ljunggren.sendgrid.api.service; + +import java.io.IOException; +import java.net.HttpURLConnection; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import io.ljunggren.sendgrid.api.exception.SendgridException; + +/** + * Service for SendGrid's unsubscribe groups (the v3 asm/groups suppressions endpoints). + */ +public class SuppressionService extends BaseService { + + /** + * Create a new {@code SuppressionService} backed by a real SendGrid client. + * + * @param apiKey the SendGrid API key + * @throws IllegalArgumentException if {@code apiKey} is null or blank + */ + public SuppressionService(String apiKey) { + super(apiKey); + } + + /** + * Test-only constructor that accepts a pre-built (possibly mocked) client. + * + * @param sendGrid the SendGrid client to use + */ + SuppressionService(SendGrid sendGrid) { + super(sendGrid); + } + + /** + * Take an address off an unsubscribe group's suppression list, so it receives that group's emails again (for + * when the person opts back in somewhere else). An address that wasn't suppressed is fine too. + * + * @param groupId unsubscribe group id + * @param email the address (must not be null or blank) + * @throws SendgridException if SendGrid refuses or can't be reached + */ + public void deleteGroupSuppression(int groupId, String email) throws SendgridException { + if (email == null || email.isBlank()) { + throw new IllegalArgumentException("email must not be null or blank"); + } + try { + Request request = new Request(); + request.setMethod(Method.DELETE); + // Not URL-encoded here: the client builds the URL from the path and encodes it itself + request.setEndpoint("asm/groups/" + groupId + "/suppressions/" + email.strip()); + Response response = sendGrid.api(request); + int status = response.getStatusCode(); + if (status == HttpURLConnection.HTTP_NO_CONTENT || status == HttpURLConnection.HTTP_OK + || status == HttpURLConnection.HTTP_NOT_FOUND) { + return; + } + throw new SendgridException("Error removing suppression. status=" + status + ", body=" + response.getBody()); + } catch (IOException e) { + throw new SendgridException("Failed to remove suppression", e); + } + } + +} diff --git a/src/test/java/io/ljunggren/sendgrid/api/service/EmailServiceTest.java b/src/test/java/io/ljunggren/sendgrid/api/service/EmailServiceTest.java index f9823e7..f9b9777 100755 --- a/src/test/java/io/ljunggren/sendgrid/api/service/EmailServiceTest.java +++ b/src/test/java/io/ljunggren/sendgrid/api/service/EmailServiceTest.java @@ -122,6 +122,34 @@ verify(sendGrid, times(1)).api(any(Request.class)); } + @Test + void sendTemplateEmail_withGroup_addsTheUnsubscribeGroup() throws Exception { + Response response = new Response(); + response.setStatusCode(202); + when(sendGrid.api(any(Request.class))).thenReturn(response); + + service.sendTemplateEmail("tpl-1", "from@x.com", "to@y.com", Map.of("name", "World"), 4321); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + verify(sendGrid).api(captor.capture()); + String body = captor.getValue().getBody(); + assertEquals(true, body.contains("\"asm\":{\"group_id\":4321,\"groups_to_display\":[4321]}"), body); + assertEquals(true, body.contains("\"template_id\":\"tpl-1\""), body); + } + + @Test + void sendTemplateEmail_withoutGroup_hasNoUnsubscribeGroup() throws Exception { + Response response = new Response(); + response.setStatusCode(202); + when(sendGrid.api(any(Request.class))).thenReturn(response); + + service.sendTemplateEmail("tpl-1", "from@x.com", "to@y.com", null, null); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + verify(sendGrid).api(captor.capture()); + assertEquals(false, captor.getValue().getBody().contains("asm")); + } + @ParameterizedTest @NullAndEmptySource @ValueSource(strings = { " " }) diff --git a/src/test/java/io/ljunggren/sendgrid/api/service/SuppressionServiceTest.java b/src/test/java/io/ljunggren/sendgrid/api/service/SuppressionServiceTest.java new file mode 100644 index 0000000..abace11 --- /dev/null +++ b/src/test/java/io/ljunggren/sendgrid/api/service/SuppressionServiceTest.java @@ -0,0 +1,78 @@ +package io.ljunggren.sendgrid.api.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import com.sendgrid.Method; +import com.sendgrid.Request; +import com.sendgrid.Response; +import com.sendgrid.SendGrid; + +import io.ljunggren.sendgrid.api.exception.SendgridException; + +class SuppressionServiceTest { + + private SendGrid sendGrid; + private SuppressionService service; + + @BeforeEach + void setUp() { + sendGrid = org.mockito.Mockito.mock(SendGrid.class); + service = new SuppressionService(sendGrid); + } + + private void respond(int status) throws IOException { + Response response = new Response(); + response.setStatusCode(status); + response.setBody("{}"); + when(sendGrid.api(any(Request.class))).thenReturn(response); + } + + @ParameterizedTest + @ValueSource(ints = { 204, 200, 404 }) + void deleteGroupSuppression_deletesFromTheGroup(int status) throws Exception { + respond(status); + + service.deleteGroupSuppression(4321, "dave@example.com"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + verify(sendGrid).api(captor.capture()); + assertEquals(Method.DELETE, captor.getValue().getMethod()); + assertEquals("asm/groups/4321/suppressions/dave@example.com", captor.getValue().getEndpoint()); + } + + @Test + void deleteGroupSuppression_otherStatus_throws() throws Exception { + respond(401); + SendgridException ex = assertThrows(SendgridException.class, + () -> service.deleteGroupSuppression(1, "dave@example.com")); + assertEquals(true, ex.getMessage().contains("401")); + } + + @Test + void deleteGroupSuppression_ioException_isWrapped() throws Exception { + IOException ioe = new IOException("network down"); + when(sendGrid.api(any(Request.class))).thenThrow(ioe); + SendgridException ex = assertThrows(SendgridException.class, + () -> service.deleteGroupSuppression(1, "dave@example.com")); + assertSame(ioe, ex.getCause()); + } + + @Test + void deleteGroupSuppression_rejectsBlankEmail() { + assertThrows(IllegalArgumentException.class, () -> service.deleteGroupSuppression(1, " ")); + } + +}