com.sendgrid.SendGrid Java Examples

The following examples show how to use com.sendgrid.SendGrid. 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: OghamSpringBoot1AutoConfigurationTests.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void oghamAlone() throws Exception {
	context.register(OghamSpringBoot1AutoConfiguration.class);
	context.refresh();
	MessagingService messagingService = context.getBean(MessagingService.class);
	checkEmail(messagingService);
	checkSms(messagingService);
	OghamInternalAssertions.assertThat(messagingService)
		.sendGrid()
			.apiKey(equalTo("ogham"))
			.client(allOf(isA(SendGrid.class), not(isSpringBeanInstance(context, SendGrid.class))))
			.and()
		.thymeleaf()
			.all()
				.engine(isA(TemplateEngine.class))
				.and()
			.and()
		.freemarker()
			.all()
				.configuration()
					.defaultEncoding(equalTo(StandardCharsets.US_ASCII.name()));
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: OghamSpringBoot2AutoConfigurationTests.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void oghamAlone() throws Exception {
	contextRunner = contextRunner.withConfiguration(of(OghamSpringBoot2AutoConfiguration.class));
	contextRunner.run((context) -> {
		MessagingService messagingService = context.getBean(MessagingService.class);
		checkEmail(messagingService);
		checkSms(messagingService);
		OghamInternalAssertions.assertThat(messagingService)
			.sendGrid()
				.apiKey(equalTo("ogham"))
				.client(allOf(isA(SendGrid.class), not(isSpringBeanInstance(context, SendGrid.class))))
				.and()
			.thymeleaf()
				.all()
					.engine(isA(TemplateEngine.class))
					.and()
				.and()
			.freemarker()
				.all()
					.configuration()
						.defaultEncoding(equalTo(StandardCharsets.US_ASCII.name()));
	});
}
 
Example #8
Source File: PriorizedContentHandler.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Override
public void setContent(final Email original, final SendGrid.Email email, final Content content) throws ContentHandlerException {
	if (email == null) {
		throw new IllegalArgumentException("[email] cannot be null");
	}
	if (content == null) {
		throw new IllegalArgumentException("[content] cannot be null");
	}

	final Class<?> clazz = content.getClass();
	LOG.debug("Getting content handler for type {}", clazz);
	final SendGridContentHandler handler = findHandler(content);
	if (handler == null) {
		LOG.warn("No content handler found for requested type {}", clazz);
		throw new ContentHandlerException("No content handler found for content type " + clazz.getSimpleName(), content);
	} else {
		handler.setContent(original, email, content);
	}
}
 
Example #9
Source File: MultiContentHandler.java    From ogham with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the content and adds it into the email. This method is expected to
 * update the content of the {@code email} parameter.
 * 
 * While the method signature accepts any {@link Content} instance as
 * parameter, the method will fail if anything other than a
 * {@link MultiContent} is provided.
 * 
 * @param email
 *            the email to put the content in
 * @param content
 *            the unprocessed content
 * @throws ContentHandlerException
 *             the handler is unable to add the content to the email
 * @throws IllegalArgumentException
 *             the content provided is not of the right type
 */
@Override
public void setContent(final Email original, final SendGrid.Email email, final Content content) throws ContentHandlerException {
	if (email == null) {
		throw new IllegalArgumentException("[email] cannot be null");
	}
	if (content == null) {
		throw new IllegalArgumentException("[content] cannot be null");
	}

	if (content instanceof MultiContent) {
		for (Content subContent : ((MultiContent) content).getContents()) {
			delegate.setContent(original, email, subContent);
		}
	} else {
		throw new IllegalArgumentException("This instance can only work with MultiContent instances, but was passed " + content.getClass().getSimpleName());
	}
}
 
Example #10
Source File: StringContentHandler.java    From ogham with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the content and adds it into the email. This method is expected to
 * update the content of the {@code email} parameter.
 * 
 * While the method signature accepts any {@link Content} instance as
 * parameter, the method will fail if anything other than a
 * {@link StringContent} is provided.
 * 
 * @param email
 *            the email to put the content in
 * @param content
 *            the unprocessed content
 * @throws ContentHandlerException
 *             the handler is unable to add the content to the email
 * @throws IllegalArgumentException
 *             the content provided is not of the right type
 */
@Override
public void setContent(final Email original, final SendGrid.Email email, final Content content) throws ContentHandlerException {
	if (email == null) {
		throw new IllegalArgumentException("[email] cannot be null");
	}
	if (content == null) {
		throw new IllegalArgumentException("[content] cannot be null");
	}

	if (content instanceof MayHaveStringContent && ((MayHaveStringContent) content).canProvideString()) {
		final String contentStr = ((MayHaveStringContent) content).asString();

		try {
			final String mime = mimeProvider.detect(contentStr).toString();
			LOG.debug("Email content has detected type {}", mime);
			LOG.trace("content: {}", content);
			setMimeContent(email, contentStr, mime, content);
		} catch (MimeTypeDetectionException e) {
			throw new ContentHandlerException("Unable to set the email content", content, e);
		}
	} else {
		throw new IllegalArgumentException("This instance can only work with MayHaveStringContent instances, but was passed " + content.getClass().getSimpleName());
	}

}
 
Example #11
Source File: OghamSpringBoot2AutoConfigurationTests.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void oghamInWebContext() throws Exception {
	contextRunner = contextRunner.withConfiguration(of(WebMvcAutoConfiguration.class, OghamSpringBoot2AutoConfiguration.class));
	contextRunner.run((context) -> {
		MessagingService messagingService = context.getBean(MessagingService.class);
		checkEmail(messagingService);
		checkSms(messagingService);
		OghamInternalAssertions.assertThat(messagingService)
			.sendGrid()
				.apiKey(equalTo("ogham"))
				.client(allOf(isA(SendGrid.class), not(isSpringBeanInstance(context, SendGrid.class))))
				.and()
			.thymeleaf()
				.all()
					.engine(isA(TemplateEngine.class))
					.and()
				.and()
			.freemarker()
				.all()
					.configuration()
						.defaultEncoding(equalTo(StandardCharsets.US_ASCII.name()));
	});
}
 
Example #12
Source File: OghamSpringBoot1AutoConfigurationTests.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Test
public void oghamInWebContext() throws Exception {
	context.register(WebMvcAutoConfiguration.class, OghamSpringBoot1AutoConfiguration.class);
	context.refresh();
	MessagingService messagingService = context.getBean(MessagingService.class);
	checkEmail(messagingService);
	checkSms(messagingService);
	OghamInternalAssertions.assertThat(messagingService)
		.sendGrid()
			.apiKey(equalTo("ogham"))
			.client(allOf(isA(SendGrid.class), not(isSpringBeanInstance(context, SendGrid.class))))
			.and()
		.thymeleaf()
			.all()
				.engine(isA(TemplateEngine.class))
				.and()
			.and()
		.freemarker()
			.all()
				.configuration()
					.defaultEncoding(equalTo(StandardCharsets.US_ASCII.name()));
}
 
Example #13
Source File: SendGridAssertions.java    From ogham with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "squid:S1166", "unchecked" })
private static String getApiKeyFromFieldOrHeaders(SendGrid client) throws IllegalAccessException {
	try {
		return (String) readField(client, "apiKey", true);
	} catch (IllegalArgumentException e) {
		Map<String, String> requestHeaders = (Map<String, String>) readField(client, "requestHeaders", true);
		String authHeader = requestHeaders.get("Authorization");
		if (authHeader == null) {
			return null;
		}
		String apiKey = authHeader.substring(7);
		// special case to be compatible with previous versions
		if ("null".equals(apiKey)) {
			return null;
		}
		return apiKey;
	}
}
 
Example #14
Source File: PriorizedContentHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test(expected = ContentHandlerException.class)
public void setContent_noMatchingHandler() throws ContentHandlerException {
	final SendGrid.Email email = new SendGrid.Email();
	final StringContent content = new StringContent("Insignificant");

	instance.setContent(null, email, content);
}
 
Example #15
Source File: StringContentHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test
public void setContent_text() throws ContentHandlerException, MimeTypeDetectionException, MimeTypeParseException {
	final SendGrid.Email email = new SendGrid.Email();

	final MimeType mime = new MimeType("text/plain");
	when(provider.detect(CONTENT_TEXT)).thenReturn(mime);

	instance.setContent(null, email, content);

	assertEquals("The email was not correctly updated", CONTENT_TEXT, email.getText());
}
 
Example #16
Source File: StringContentHandler.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static void setMimeContent(final SendGrid.Email email, final String contentStr, final String mime, Content content) throws ContentHandlerException {
	if ("text/plain".equals(mime)) {
		email.setText(contentStr);
	} else if ("text/html".equals(mime)) {
		email.setHtml(contentStr);
	} else {
		throw new ContentHandlerException("MIME type " + mime + " is not supported", content);
	}
}
 
Example #17
Source File: MultiContentHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test
public void setContent_multiple() throws ContentHandlerException {
	final Content exp1 = new StringContent("Insignificant 1");
	final Content exp2 = new StringContent("Insignificant 2");
	final Content content = new MultiContent(exp1, exp2);
	final SendGrid.Email email = new SendGrid.Email();

	instance.setContent(null, email, content);

	verify(delegate).setContent(any(), any(SendGrid.Email.class), eq(exp1));
	verify(delegate).setContent(any(), any(SendGrid.Email.class), eq(exp2));
}
 
Example #18
Source File: MultiContentHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void setContent_notMultiContent() throws ContentHandlerException {
	final Content content = new StringContent("Insignificant");
	final SendGrid.Email email = new SendGrid.Email();

	instance.setContent(null, email, content);
}
 
Example #19
Source File: MultiContentHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test(expected = ContentHandlerException.class)
public void setContent_delegateFailure() throws ContentHandlerException {
	final Content exp = new StringContent("Insignificant");
	final Content content = new MultiContent(exp);
	final SendGrid.Email email = new SendGrid.Email();

	final ContentHandlerException e = new ContentHandlerException("Thrown by mock", exp);
	doThrow(e).when(delegate).setContent(null, email, exp);
	instance.setContent(null, email, content);
}
 
Example #20
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 #21
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 #22
Source File: MultiContentHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test
public void setContent_single() throws ContentHandlerException {
	final Content exp = new StringContent("Insignificant");
	final Content content = new MultiContent(exp);
	final SendGrid.Email email = new SendGrid.Email();

	instance.setContent(null, email, content);

	verify(delegate).setContent(any(), any(SendGrid.Email.class), eq(exp));
}
 
Example #23
Source File: PriorizedContentHandlerTest.java    From ogham with Apache License 2.0 5 votes vote down vote up
@Test
public void setContent() throws ContentHandlerException {
	instance.register(StringContent.class, handler);

	final SendGrid.Email email = new SendGrid.Email();
	final StringContent content = new StringContent("Insignificant");

	instance.setContent(null, email, content);

	verify(handler).setContent(null, email, content);
}
 
Example #24
Source File: SendGridV2Builder.java    From ogham with Apache License 2.0 5 votes vote down vote up
private SendGrid buildSendGrid(String apiKey, String username, String password, URL url) {
	SendGrid sendGrid = newSendGrid(apiKey, username, password);
	if (url != null) {
		sendGrid.setUrl(url.toString());
	}
	if (httpClient != null) {
		sendGrid.setClient(httpClient);
	}
	return sendGrid;
}
 
Example #25
Source File: SendGridSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public void open() throws SenderException {
	super.open();
	httpclient.open();

	CloseableHttpClient httpClient = httpclient.getHttpClient();
	if(httpClient == null)
		throw new SenderException("no HttpClient found, did it initialize properly?");

	Client client = new Client(httpClient);
	sendGrid = new SendGrid(getCredentialFactory().getPassword(), client);
}
 
Example #26
Source File: SendEmailServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {


    // Set content for request.
    Email to = new Email(TO_EMAIL);
    Email from = new Email(SENDGRID_SENDER);
    String subject = "This is a test email";
    Content content = new Content("text/plain", "Example text body.");
    Mail mail = new Mail(from, subject, to, content);

    // Instantiates SendGrid client.
    SendGrid sendgrid = new SendGrid(SENDGRID_API_KEY);

    // Instantiate SendGrid request.
    Request request = new Request();

    // Set request configuration.
    request.setMethod(Method.POST);
    request.setEndpoint("mail/send");
    request.setBody(mail.build());

    // Use the client to send the API request.
    Response response = sendgrid.api(request);

    if (response.getStatusCode() != 202) {
      System.out.print(String.format("An error occurred: %s", response.getStatusCode()));
      return;
    }

    System.out.print("Email sent.");
  }
 
Example #27
Source File: SendGridV2Sender.java    From ogham with Apache License 2.0 5 votes vote down vote up
private static void addAttachment(final SendGrid.Email ret, final Attachment attachment) throws AttachmentReadException {
	try {
		ret.addAttachment(attachment.getResource().getName(), attachment.getResource().getInputStream());
		// TODO: how to set Content-Type per attachment with SendGrid v2 API ?
		if (attachment.getContentId() != null) {
			String id = CID.matcher(attachment.getContentId()).replaceAll("$1");
			ret.addContentId(attachment.getResource().getName(), id);
		}
	} catch (IOException e) {
		throw new AttachmentReadException("Failed to attach email attachment named " + attachment.getResource().getName(), attachment, e);
	}
}
 
Example #28
Source File: SendGridV2Sender.java    From ogham with Apache License 2.0 5 votes vote down vote up
private SendGrid.Email toSendGridEmail(final Email message) throws ContentHandlerException, AttachmentReadException {
	final SendGrid.Email ret = new SendGrid.Email();
	ret.setSubject(message.getSubject());

	ret.setFrom(message.getFrom().getAddress());
	ret.setFromName(message.getFrom().getPersonal() == null ? "" : message.getFrom().getPersonal());

	final String[] tos = new String[message.getRecipients().size()];
	final String[] toNames = new String[message.getRecipients().size()];
	int i = 0;
	for (Recipient recipient : message.getRecipients()) {
		final EmailAddress address = recipient.getAddress();
		tos[i] = address.getAddress();
		toNames[i] = address.getPersonal() == null ? "" : address.getPersonal();
		i++;
	}
	ret.setTo(tos);
	ret.setToName(toNames);

	handler.setContent(message, ret, message.getContent());

	for (Attachment attachment : message.getAttachments()) {
		addAttachment(ret, attachment);
	}

	return ret;
}
 
Example #29
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 #30
Source File: SendgridService.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
@Override
public EmailSendingStatus sendEmail(EmailWrapper wrapper) throws IOException {
    Mail email = parseToEmail(wrapper);
    SendGrid sendgrid = new SendGrid(Config.SENDGRID_APIKEY);
    Request request = new Request();
    request.setMethod(Method.POST);
    request.setEndpoint("mail/send");
    request.setBody(email.build());
    Response response = sendgrid.api(request);
    return new EmailSendingStatus(response.getStatusCode(), response.getBody());
}