com.sendgrid.SendGridException Java Examples

The following examples show how to use com.sendgrid.SendGridException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EmailSendGridNotificationHandler.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
private void send(String recipient, Email email) {
    if (StringUtils.isBlank(cfg.getIdentity().getFrom())) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " +
                "You must set a value for notifications to work");
    }

    try {
        email.addTo(recipient);
        email.setFrom(cfg.getIdentity().getFrom());
        email.setFromName(cfg.getIdentity().getName());
        Response response = sendgrid.send(email);
        if (response.getStatus()) {
            log.info("Successfully sent email to {} using SendGrid", recipient);
        } else {
            throw new RuntimeException("Error sending via SendGrid to " + recipient + ": " + response.getMessage());
        }
    } catch (SendGridException e) {
        throw new RuntimeException("Unable to send e-mail invite via SendGrid to " + recipient, e);
    }
}
 
Example #2
Source File: SendGridClient.java    From vics with MIT License 6 votes vote down vote up
private Try<EmailResponse> sendEmail(Email email) {
    String recipients = Arrays.toString(email.getTos());
    try {
        Response response = sendGrid.send(email);
        if (!response.getStatus()) {
            log.info(String.format("Failed to send password reset notification to %s (using SendGrid). %s", recipients, response.getMessage()));
            return failure(new PasswordNotificationFailure("Failed to send password to username " + recipients));
        } else {
            log.info(String.format("Sent email to %s", recipients));
            return success(ImmutableEmailResponse.builder().withMessage(response.getMessage()).build());
        }
    } catch (SendGridException e) {
        log.error(String.format("Failed to contact SendGrid to send password reset notification. Recipients=%s", recipients), e);
        return failure(new SendGridApiFailure("Failed to send password"));
    }
}
 
Example #3
Source File: DelegateSendGridClient.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Override
public void send(final Email email) throws SendGridException {
	if (email == null) {
		throw new IllegalArgumentException("[email] cannot be null");
	}

	LOG.debug("Sending to SendGrid client: FROM {}<{}>", email.getFromName(), email.getFrom());
	LOG.debug("Sending to SendGrid client: TO {} (as {})", email.getTos(), email.getToNames());
	LOG.debug("Sending to SendGrid client: SUBJECT {}", email.getSubject());
	LOG.debug("Sending to SendGrid client: TEXT CONTENT {}", email.getText());
	LOG.debug("Sending to SendGrid client: HTML CONTENT {}", email.getHtml());

	final SendGrid.Response response = delegate.send(email);

	if (response.getStatus()) {
		LOG.debug("Response from SendGrid client: ({}) {}", response.getCode(), response.getMessage());
	} else {
		throw new SendGridException(new IOException("Sending to SendGrid failed: (" + response.getCode() + ") " + response.getMessage()));
	}
}
 
Example #4
Source File: SendGridTranslationTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void forBasicTextEmail() throws MessagingException, SendGridException {
	// @formatter:off
	final Email email = new Email()
								.subject(SUBJECT)
								.content(CONTENT_TEXT)
								.from(new EmailAddress(FROM_ADDRESS, FROM))
								.to(new EmailAddress(TO_ADDRESS_1, TO));
	// @formatter:on

	messagingService.send(email);

	final ArgumentCaptor<SendGrid.Email> argument = ArgumentCaptor.forClass(SendGrid.Email.class);
	verify(sendGridClient).send(argument.capture());
	final SendGrid.Email val = argument.getValue();

	assertEquals(SUBJECT, val.getSubject());
	assertEquals(FROM, val.getFromName());
	assertEquals(FROM_ADDRESS, val.getFrom());
	assertEquals(TO, val.getToNames()[0]);
	assertEquals(TO_ADDRESS_1, val.getTos()[0]);
	assertEquals(CONTENT_TEXT, val.getText());
}
 
Example #5
Source File: SendGridTranslationTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void forAccentedTextEmail() throws MessagingException, SendGridException {
	// @formatter:off
	final Email email = new Email()
								.subject(SUBJECT)
								.content(new StringContent(CONTENT_TEXT_ACCENTED))
								.from(new EmailAddress(FROM_ADDRESS, FROM))
								.to(new EmailAddress(TO_ADDRESS_1, TO));
	// @formatter:on

	messagingService.send(email);

	final ArgumentCaptor<SendGrid.Email> argument = ArgumentCaptor.forClass(SendGrid.Email.class);
	verify(sendGridClient).send(argument.capture());
	final SendGrid.Email val = argument.getValue();

	assertEquals(SUBJECT, val.getSubject());
	assertEquals(FROM, val.getFromName());
	assertEquals(FROM_ADDRESS, val.getFrom());
	assertEquals(TO, val.getToNames()[0]);
	assertEquals(TO_ADDRESS_1, val.getTos()[0]);
	assertEquals(CONTENT_TEXT_ACCENTED, val.getText());
}
 
Example #6
Source File: SendGridTranslationTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void forBasicHtmlEmail() throws MessagingException, SendGridException {
	// @formatter:off
	final Email email = new Email()
								.subject(SUBJECT)
								.content(new StringContent(CONTENT_HTML))
								.from(new EmailAddress(FROM_ADDRESS, FROM))
								.to(new EmailAddress(TO_ADDRESS_1, TO));
	// @formatter:on

	messagingService.send(email);

	final ArgumentCaptor<SendGrid.Email> argument = ArgumentCaptor.forClass(SendGrid.Email.class);
	verify(sendGridClient).send(argument.capture());
	final SendGrid.Email val = argument.getValue();

	assertEquals(SUBJECT, val.getSubject());
	assertEquals(FROM, val.getFromName());
	assertEquals(FROM_ADDRESS, val.getFrom());
	assertEquals(TO, val.getToNames()[0]);
	assertEquals(TO_ADDRESS_1, val.getTos()[0]);
	assertEquals(CONTENT_HTML, val.getHtml());
}
 
Example #7
Source File: SendGridTranslationTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void forTemplatedTextEmail() throws MessagingException, SendGridException {
	// @formatter:off
	final Email email = new Email()
								.subject(SUBJECT)
								.content(new TemplateContent("string:" + CONTENT_TEXT_TEMPLATE, new SimpleContext("name", NAME)))
								.from(new EmailAddress(FROM_ADDRESS, FROM))
								.to(new EmailAddress(TO_ADDRESS_1, TO), new EmailAddress(TO_ADDRESS_2, TO));
	// @formatter:on

	messagingService.send(email);

	final ArgumentCaptor<SendGrid.Email> argument = ArgumentCaptor.forClass(SendGrid.Email.class);
	verify(sendGridClient).send(argument.capture());
	final SendGrid.Email val = argument.getValue();

	assertEquals(SUBJECT, val.getSubject());
	assertEquals(FROM, val.getFromName());
	assertEquals(FROM_ADDRESS, val.getFrom());
	assertArrayEquals(new String[] { TO, TO }, val.getToNames());
	assertArrayEquals(new String[] { TO_ADDRESS_1, TO_ADDRESS_2 }, val.getTos());
	assertEquals(CONTENT_TEXT_RESULT, val.getText());
}
 
Example #8
Source File: SendGridTranslationTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void forTemplatedHtmlEmail() throws MessagingException, SendGridException {
	// @formatter:off
	final Email email = new Email()
								.subject(SUBJECT)
								.content(new TemplateContent("string:" + CONTENT_HTML_TEMPLATE, new SimpleContext("name", NAME)))
								.from(new EmailAddress(FROM_ADDRESS, FROM))
								.to(new EmailAddress(TO_ADDRESS_1, TO), new EmailAddress(TO_ADDRESS_2, TO));
	// @formatter:on

	messagingService.send(email);

	final ArgumentCaptor<SendGrid.Email> argument = ArgumentCaptor.forClass(SendGrid.Email.class);
	verify(sendGridClient).send(argument.capture());
	final SendGrid.Email val = argument.getValue();

	assertEquals(SUBJECT, val.getSubject());
	assertEquals(FROM, val.getFromName());
	assertEquals(FROM_ADDRESS, val.getFrom());
	assertArrayEquals(new String[] { TO, TO }, val.getToNames());
	assertArrayEquals(new String[] { TO_ADDRESS_1, TO_ADDRESS_2 }, val.getTos());
	assertEquals(CONTENT_HTML_RESULT, val.getHtml());
}
 
Example #9
Source File: SendGridHttpTest.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void authenticationFailed() throws MessagingException, JsonParseException, JsonMappingException, IOException {
	// @formatter:off
	server.stubFor(post("/api/mail.send.json")
		.willReturn(aResponse()
				.withStatus(400)
				.withBody(loadJson("/stubs/responses/authenticationFailed.json"))));
	// @formatter:on
	// @formatter:off
	Email email = new Email()
		.subject(SUBJECT)
		.content(CONTENT_TEXT)
		.from(FROM_ADDRESS)
		.to(TO_ADDRESS_1);
	// @formatter:on
	
	MessagingException e = assertThrows(MessagingException.class, () -> {
		messagingService.send(email);
	}, "throws message exception");
	assertThat("sendgrid exception", e.getCause(), allOf(notNullValue(), instanceOf(SendGridException.class)));
	assertThat("root cause", e.getCause().getCause(), allOf(notNullValue(), instanceOf(IOException.class)));
	assertThat("sendgrid message", e.getCause().getCause().getMessage(), Matchers.equalTo("Sending to SendGrid failed: (400) {\n" + 
			"	\"errors\": [\"The provided authorization grant is invalid, expired, or revoked\"],\n" + 
			"	\"message\": \"error\"\n" + 
			"}"));
}
 
Example #10
Source File: SendGridClientTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test
public void send() throws SendGridException {
	final SendGrid.Response response = new SendGrid.Response(200, "OK");
	final SendGrid.Email exp = new SendGrid.Email();

	when(delegate.send(exp)).thenReturn(response);

	instance.send(exp);

	verify(delegate).send(exp);
}
 
Example #11
Source File: SendGridClientTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test(expected = SendGridException.class)
public void send_errorResponse() throws SendGridException {
	final SendGrid.Response response = new SendGrid.Response(403, "FORBIDDEN");
	final SendGrid.Email exp = new SendGrid.Email();

	when(delegate.send(exp)).thenReturn(response);

	instance.send(exp);
}
 
Example #12
Source File: MainActivity.java    From sendgrid-android with MIT License 5 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {

  try {
    SendGrid sendgrid = new SendGrid(SENDGRID_USERNAME, SENDGRID_PASSWORD);

    SendGrid.Email email = new SendGrid.Email();

    // Get values from edit text to compose email
    // TODO: Validate edit texts
    email.addTo(mTo);
    email.setFrom(mFrom);
    email.setSubject(mSubject);
    email.setText(mText);

    // Attach image
    if (mUri != null) {
      email.addAttachment(mAttachmentName, mAppContext.getContentResolver().openInputStream(mUri));
    }

    // Send email, execute http request
    SendGrid.Response response = sendgrid.send(email);
    mMsgResponse = response.getMessage();

    Log.d("SendAppExample", mMsgResponse);

  } catch (SendGridException | IOException e) {
    Log.e("SendAppExample", e.toString());
  }

  return null;
}
 
Example #13
Source File: MailSender.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
public void sendUsingSendGrid(String from, String to, String subject, String msg) {
Email email = new Email();
email.setFrom(from);
email.addTo(to);
email.setSubject(subject);
email.setText(msg);

try {
    sendGrid.send(email);
} catch (SendGridException e) {
    logger.error(e.getMessage(), e);
}
   }
 
Example #14
Source File: SendGridEmailService.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
@Override
public void send(String toAddress, String subject, String htmlContent) {
    SendGrid.Email email = new SendGrid.Email();
    email.setSubject(subject);
    email.setHtml(htmlContent);

    email.setFrom(config.getFromEmail());
    email.setFromName(config.getFromName());

    if (!Strings.isNullOrEmpty(config.getOverrideReceiver())) {
        email.addTo(config.getOverrideReceiver());
    } else {
        email.addTo(toAddress);
    }

    try {
        SendGrid.Response response = sendGrid.send(email);

        if (!response.getStatus()) {
            metrics.meter(MetricRegistry.name("email", "send", "failure", toMetricName(toAddress))).mark();
            log.error("Error sending email via SendGrid:", response.getMessage());
        } else {
            metrics.meter(MetricRegistry.name("email", "send", "success", toMetricName(toAddress))).mark();
        }
    } catch (SendGridException e) {
        metrics.meter(MetricRegistry.name("email", "send", "failure", toMetricName(toAddress))).mark();
        log.error("Error sending email via SendGrid:", e);
    }
}
 
Example #15
Source File: SendGridClientTest.java    From ogham with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void sendEmailParamCannotBeNull() throws SendGridException {
	instance.send(null);
}
 
Example #16
Source File: SendGridClient.java    From ogham with Apache License 2.0 2 votes vote down vote up
/**
 * Sends the provided email to SendGrid.
 * 
 * @param email
 *            the email to send, cannot be {@code null}
 * @throws SendGridException
 *             an unexpected error occurred when trying to send the email
 */
void send(SendGrid.Email email) throws SendGridException;