Newer
Older
sendgrid-api / src / main / java / io / ljunggren / sendgrid / api / service / EmailService.java
package io.ljunggren.sendgrid.api.service;

import java.io.IOException;
import java.util.Map;

import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;

import io.ljunggren.sendgrid.api.exception.SendgridException;

public class EmailService extends BaseService {

	public EmailService(String apiKey) {
		super(apiKey);
	}

	public void sendEmail(String from, String to, String subject, String body) throws SendgridException {
		Mail mail = new Mail(
				new Email(from), 
				subject, 
				new Email(to), 
				new Content("text/plain", body));
		sendEmail(mail);
	}
	
	public void sendTemplateEmail(String templateId, String from, String to, Map<String, Object> templateData) throws SendgridException {
		Mail mail = new Mail();
		mail.setTemplateId(templateId);
		mail.setFrom(new Email(from));
		Personalization personalization = new Personalization();
		personalization.addTo(new Email(to));
		templateData.entrySet().stream().forEach(entry -> personalization.addDynamicTemplateData(entry.getKey(), entry.getValue()));
		mail.addPersonalization(personalization);
		sendEmail(mail);
	}
	
	private void sendEmail(Mail mail) throws SendgridException {
		try {
			Request request = new Request();
			request.setMethod(Method.POST);
			request.setEndpoint("mail/send");
			request.setBody(mail.build());
			Response response = sendGrid.api(request);
			if (response.getStatusCode() == 202) {
				return;
			}
			throw new SendgridException("Error sending email: " + response.getBody());
		} catch (IOException e) {
			throw new SendgridException(e.getMessage());
		}
	}
	
}