Mailgun Java API发送HTML电子邮件

时间:2018-06-27 01:29:51

标签: java html email mailgun unirest

我正在尝试 Java中的"html": "... entire contents of HTML page goes here ..."使用了与MailGun API的Unirest HTTP通信。

到目前为止,我已经验证了我的域,已通过API成功发送了电子邮件,并已通过Java中的API成功发送了HTML(基本)电子邮件。 每当我尝试使用任何电子邮件模板时,都无法发送电子邮件(通过Java中的API)发送电子邮件。我正在尝试使用以下推荐的电子邮件模板:https://github.com/mailgun/transactional-email-templates/tree/master/templates

我发送电子邮件的代码与文档一致

public static JsonNode sendSimpleMessage() throws UnirestException {
        HttpResponse<com.mashape.unirest.http.JsonNode> request = Unirest.post("https://api.mailgun.net/v3/sub.domain.com" + "/messages")
                .basicAuth("api",  API_KEY)
                .queryString("from", "name <test@domain.com>")
                .queryString("to", "myemail@gmail.com")
                .queryString("subject", "Great")
                .queryString("html", returnEmail())
                .asJson();

        return request.getBody();
    }

public static String returnEmail() {
        try {
            return StreamUtils.copyToString(new ClassPathResource("email.html").getInputStream(), Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "<html><strong>not today</strong></html>";
    }

email.html包含上述电子邮件(https://github.com/mailgun/transactional-email-templates/tree/master/templates)或任何HTML电子邮件中的示例,但没有用。

我得到的错误是:

com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1].

Stacktrace:

com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143)
at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
at com..application.ApplicationController.sendSimpleMessage(ApplicationController.java:78)
at com.application.ApplicationController.create(ApplicationController.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:106)
    at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:139)
    ... 57 more
Caused by: java.lang.RuntimeException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:51)
    at com.mashape.unirest.http.HttpResponse.<init>(HttpResponse.java:95)
    ... 58 more
Caused by: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
    at org.json.JSONArray.<init>(JSONArray.java:105)
    at org.json.JSONArray.<init>(JSONArray.java:144)
    at com.mashape.unirest.http.JsonNode.<init>(JsonNode.java:48)
    ... 59 more

如果我只是将所有HTML粘贴为字符串而不是returnEmail(),也会遇到相同的错误。如果在发送前转义特殊字符和/或缩小HTML,也会收到相同的错误消息。

现在,我假设Unirest是一个http库,因此它将根据queryString键和值构建一个JSON。虽然它似乎可以与Simpel html一起使用,例如“ HTML版本任何”,但它当然不喜欢任何冗长/“普通”的html,例如电子邮件模板。

您能为使用Java API的html电子邮件提供任何可行的示例或有关如何发送html并具有有效json的任何提示吗?

一吨

3 个答案:

答案 0 :(得分:4)

从所报告的错误消息中:

org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1].

我不确定Unirest正在尝试做什么,但似乎正在尝试将某些内容编码为JSON。但是Mailgun API不需要JSON编码,使用旧的application/x-www-form-urlencoded编码就可以了。请查阅Unirest文档,以查看是否可以强制使用其他编码类型。

或者,您也可以按照问题评论中的说明使用this other library(免责声明:我是开发人员)。 OP抱怨不适用于here 所述的复杂html。我的意思是存在内容帮助程序机制,您可以在其中使用链接的方法调用(DSL样式)来构建HTML内容。如果您已经有了HTML,则只需将其传递给html()方法调用即可,如注释中所述。

您的代码看起来像这样:

// somewhere else
Configuration configuration = new Configuration()
    .domain("sub.domain.com")
    .apiKey(API_KEY)
    .from("name", "test@domain.com");

public static void sendSimpleMessage() {
    Mail.using(configuration)
        .to("myemail@gmail.com")
        .subject("Great")
        .html(returnEmail())
        .build()
        .send();
}

答案 1 :(得分:1)

尝试通过Unirest.post(...)。queryString(“ html”,bulkStringHere).. asJson();. p

发布大型HTML文档时,我遇到了相同的错误。

,发现“ com.mashape.unirest.http.exceptions.UnirestException:java.lang.RuntimeException:java.lang.RuntimeException:org.json.JSONException:JSONArray文本必须以'['开头[[字符2行1]“

实际上是尝试将响应解析为JSON的结果。将asJson()更改为asString(),您将看到Mailgun给您的实际错误:

<html>
<head><title>414 Request-URI Too Large</title></head>
<body bgcolor="white">
<center><h1>414 Request-URI Too Large</h1></center>
<hr><center>nginx</center>
</body>
</html>

这是因为Unirest让您将html正文添加为queryString,这超出了Nginx中配置的允许的查询字符串长度。我尝试将Content更改为以url编码的形式,并使用.field(“ html”,MassiveStringHere),但这没有按我预期的那样工作。为什么必须在URL中指定POST的所有字段,这是设计缺陷IMO。我还没有找到解决方法,但是可以尝试这里给出的建议。.希望不求助于使用MIME路由:-/

更新:经过确认的https://github.com/sargue/mailgun是Mailgun集成的一种方式,并且不受明显困扰Unirest的HTML大小限制的困扰。只需几分钟即可轻松集成。

答案 2 :(得分:0)

从您共享的html文件中,在正文中使用html,删除所有其他标签,发布后应该可以正常工作。

例如。来自文件-https://github.com/mailgun/transactional-email-templates/blob/master/templates/alert.html

仅使用以下提到的html。

<table class="body-wrap">
    <tr>
        <td></td>
        <td class="container" width="600">
            <div class="content">
                <table class="main" width="100%" cellpadding="0" cellspacing="0">
                    <tr>
                        <td class="alert alert-warning">
                            Warning: You're approaching your limit. Please upgrade.
                        </td>
                    </tr>
                    <tr>
                        <td class="content-wrap">
                            <table width="100%" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td class="content-block">
                                        You have <strong>1 free report</strong> remaining.
                                    </td>
                                </tr>
                                <tr>
                                    <td class="content-block">
                                        Add your credit card now to upgrade your account to a premium plan to ensure you don't miss out on any reports.
                                    </td>
                                </tr>
                                <tr>
                                    <td class="content-block">
                                        <a href="http://www.mailgun.com" class="btn-primary">Upgrade my account</a>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="content-block">
                                        Thanks for choosing Acme Inc.
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
                <div class="footer">
                    <table width="100%">
                        <tr>
                            <td class="aligncenter content-block"><a href="http://www.mailgun.com">Unsubscribe</a> from these alerts.</td>
                        </tr>
                    </table>
                </div></div>
        </td>
        <td></td>
    </tr>
</table>

更新-您可以使用电子邮件中的所有html标签,只是不包括任何外部相对css或javascript链接或脚本标签。理想情况下,包括CSS在内的整个html应该在单个HTML字符串中。