import java.io.File; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class MGSample { // ... public static JsonNode sendSimpleMessage() throws UnirestException { HttpResponserequest = Unirest.post("https://api.mailgun.net/v3/" + YOUR_DOMAIN_NAME + "/messages") .basicAuth("api", API_KEY) .queryString("from", "Excited User ") .queryString("to", "[email protected]") .queryString("subject", "hello") .queryString("text", "testing") .asJson(); return request.getBody(); } }
官网文档地址: https://documentation.mailgun.com/en/latest/quickstart-sending.html#send-via-api
参数:
1、[email protected]是mailgun的账号
2、API_KEY是注册的账号里面创建的apiKey
本地测试很容易就通过了,但是放到服务器上面就报错
异常:
com.mashape.unirest.http.exceptions.UnirestException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuild erException: unable to find valid certification path to requested target
这个是证书不信任问题
处理方法就是访问上面的发送地址(https://api.mailgun.net/v3/*******.org/messages)把证书下载到服务器,然后导入到服务器上面的证书库,使用下面的命令导入就行:
keytool -import -keystore "/usr/java/jdk1.8.0_60/jre/lib/security/cacerts" -storepass changeit -keypass changeit -alias hzpt -file www.mailgun.net.crt
"www.mailgun.net.crt" 为下载下来的证书名
按上面导入到证书库后重启tomcat就可以了