SendGrid 發送郵件代碼示例

build.gradle

/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java Library project to get you started.
 * For more details take a look at the Java Libraries chapter in the Gradle
 * user guide available at https://docs.gradle.org/4.10.2/userguide/java_library_plugin.html
 */

plugins {
    // Apply the java-library plugin to add support for Java Library
    id 'java-library'
}

dependencies {
    // This dependency is exported to consumers, that is to say found on their compile classpath.
    api 'org.apache.commons:commons-math3:3.6.1'

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation 'com.google.guava:guava:23.0'
    compile group: 'com.sendgrid', name: 'sendgrid-java', version: '3.1.0'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.2'
    compile group: 'ch.qos.logback', name: 'logback-core', version: '1.1.7'
    compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.7'
    compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.1'
    // https://mvnrepository.com/artifact/com.alibaba/fastjson
    compile group: 'com.alibaba', name: 'fastjson', version: '1.2.58'
    compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.1'
    // StringUtils.isEmpty()
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'
}

// In this section you declare where to find the dependencies of your project
repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

 

SendGridProcessor.java

package rest;

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

import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Personalization;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;


public enum SendgridProcessor {
	/**
	 * sendgrid processor singleton
	 */
	INSTANCE;

	private static final String CLASSNAME = SendgridProcessor.class.getName();
	private static final Logger LOGGER = LoggerFactory.getLogger(CLASSNAME);
	private SendGrid sg;

	SendgridProcessor() {
//		sg = new SendGrid("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");
		// Full Access
		sg = new SendGrid("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");
	}

	public boolean sendEmail(Mail mail) {

		boolean isSucceed = false;
		try {
			Request request = new Request();
			request.method = Method.POST;
			request.endpoint = "mail/send";
			request.body = mail.build();
			Response response = sg.api(request);
			LOGGER.info("Response body ......" + response.body);
			LOGGER.info("Response toString ......" + response.toString());
			int statusCode = response.statusCode;
			if (statusCode != 202) {
				LOGGER.error("Fail to send unpaid invoice email, status code: {}", statusCode);
			} else {
				isSucceed = true;
				LOGGER.info("Send unpaid invoice email Success");
			}

		} catch (Exception e) {
			LOGGER.error("Error sending unpaid invoice email: \n", e);

		}
		return isSucceed;
	}
	
	public boolean sendEmailWithCustomArgs(Mail mail, Map<String, String> customArgs) {
		// apply custom args if there is any
		if (!MapUtils.isEmpty(customArgs)) {
			Personalization p = mail.getPersonalization().get(0);
			for (Map.Entry<String, String> entry : customArgs.entrySet()) {
				p.addCustomArg(entry.getKey(), entry.getValue());
			}
			mail.addPersonalization(p);
		}
		return sendEmail(mail);
	}

	/**
	 * retrieve all transactional templates
	 * @return
	 */
	public String getAllTemplates() {
		return callSendGridWithBody(Method.GET, "templates", null);
	}
	
	public String getSingleTemplate(String templateID) {
		if (templateID == null || templateID.length() == 0) {
			return "";
		}
		return callSendGridWithBody(Method.GET, "templates/" + templateID, null);
	}
	
	public String deleteBounceEmails(Set<String> emails) {
		JsonObject body = new JsonObject();
		JsonArray array = new JsonArray();

		try {
			emails.forEach(mail -> array.add(mail));
			body.add("emails", array);
		} catch (Exception e) {
		    LOGGER.info(e.getMessage());
		}
		if (array.size() > 0) {
			return callSendGridWithBody(Method.DELETE, "suppression/bounces", body.toString());
		} else {
			return null;
		}

	}
	
	/**
	 * the interface is ok
	 * @param queryParams
	 * @return
	 */
	public String getAllBouncedEmails(Map<String, String> queryParams) {
		return callSendGrid(Method.GET, "suppression/bounces", queryParams);
	}
	
	public String getAllReaddEmails(Map<String, String> queryParams) {
		return callSendGrid(Method.GET, "click/tracking", queryParams);
	}
	
	public String getApiKeysEmails(Map<String, String> queryParams) {
		return callSendGrid(Method.GET, "api_keys/read", queryParams);
	}
	public String getAllStatsEmails(Map<String, String> queryParams) {
		return callSendGrid(Method.GET, "stats/overview", queryParams);
	}
	
	public String getSendEmail(Map<String, String> queryParams) {
		return callSendGrid(Method.GET, "suppression/send", queryParams);
	}
	
	private String callSendGrid(Method method, String endpoint, Map<String, String> queryParams) {
		String result = "";
		try {
			Request request = new Request();
			request.method = method;
			request.endpoint = endpoint;
			request.queryParams = queryParams;
			Response response = sg.api(request);
			LOGGER.info("Response body ......" + response.body);
			LOGGER.info("Response toString ......" + response.toString());
			if (response.statusCode > 400) {
				LOGGER.info(
						"response status code: " + response.statusCode + ", result response " + response.body);
				return result;
			}
			result = response.body;
			LOGGER.info("response status code: " + response.statusCode);
		} catch (IOException e) {
		    LOGGER.info(e.getMessage());
		} catch (Exception e) {
		    LOGGER.info(e.getMessage());
		}
		return result;
	}
	
	private String callSendGridWithBody(Method method, String endpoint, String reqBody) {
		String result = "";
		try {
			Request request = new Request();
			request.method = method;
			request.endpoint = endpoint;
			if (reqBody != null) {
				request.body = reqBody;
			}
			Response response = sg.api(request);
			if (response.statusCode > 400) {
				LOGGER.info(
						"response status code: " + response.statusCode + ", result response " + response.body);
				return result;
			}
			result = response.body;
			LOGGER.info("response status code: " + response.statusCode);
		} catch (IOException e) {
		    LOGGER.info(e.getMessage());
		} catch (Exception e) {
		    LOGGER.info(e.getMessage());
		}
		return result;
	}
	
}

SendEmailHelper.java

package rest;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Personalization;

public class SendEmailHelper {

	public static void main(String[] args) {
		Calendar now = Calendar.getInstance();
		Calendar yesterday = Calendar.getInstance();
		yesterday.set(Calendar.HOUR_OF_DAY, 0);
		yesterday.set(Calendar.MINUTE, 0);
		yesterday.set(Calendar.SECOND, 0);
		yesterday.add(Calendar.DAY_OF_YEAR, -1);
		//Sendgrid only accept unit time stamp, thus has to divide 1000 to convert Java timestamp to unix timestamp
		String oneDayBeforeNow = String.valueOf(yesterday.getTimeInMillis() / 1000L);
		String endTimestamp = String.valueOf(now.getTimeInMillis() / 1000L);
		
        Mail mail = new Mail();
        mail.setSubject("Email subject zhong");
        mail.setFrom(new Email("[email protected]"));
//        mail.setFrom(new Email("[email protected]"));
        
        // the receivers of the email
        Personalization sendTargets = new Personalization();
  
        sendTargets.addTo(new Email("[email protected]"));
        sendTargets.addCc(new Email("[email protected]"));
        sendTargets.addTo(new Email("[email protected]"));
        mail.addPersonalization(sendTargets);
        
        String mailBody = "<html><body>郵件內容</body></html>";
        mail.addContent(new Content("text/html", mailBody));
//        return SendgridProcessor.INSTANCE.sendEmail(mail);
		Map<String, String> queryParams = new HashMap<>();
		queryParams.put("first_name", "test args1");
		queryParams.put("last_name", "test args2");
		boolean res = SendgridProcessor.INSTANCE.sendEmailWithCustomArgs(mail, queryParams);
		System.out.println("email send : " + res);
		System.out.println("-------------------------------------------------------------------------");

		queryParams = new HashMap<>();
		queryParams.put("start_time", oneDayBeforeNow);
		queryParams.put("end_time", endTimestamp);
		String result = SendgridProcessor.INSTANCE.getAllBouncedEmails(queryParams);
		System.out.println("Bounce list:" + result);
		System.out.println("-------------------------------------------------------------------------");
		
		queryParams = new HashMap<>();
		queryParams.put("start_time", oneDayBeforeNow);
		queryParams.put("end_time", endTimestamp);
		result = SendgridProcessor.INSTANCE.getAllReaddEmails(queryParams);
		System.out.println("read email" + result);
		System.out.println("-------------------------------------------------------------------------");
		
		result = SendgridProcessor.INSTANCE.getApiKeysEmails(queryParams);
		System.out.println("Api keys read email" + result);
		System.out.println("-------------------------------------------------------------------------");
		
		
		queryParams = new HashMap<>();
		queryParams.put("start_time", oneDayBeforeNow);
		queryParams.put("end_time", endTimestamp);
		result = SendgridProcessor.INSTANCE.getSendEmail(queryParams);
		System.out.println("send email list: " + result);
		System.out.println("-------------------------------------------------------------------------");
		
		queryParams = new HashMap<>();
		queryParams.put("start_date", "2019-05-15");
		queryParams.put("end_time", "2019-05-20");
		result = SendgridProcessor.INSTANCE.getAllStatsEmails(queryParams);
		System.out.println("stats list:" + result);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章