【问题标题】:Mailgun Java API send HTML emailsMailgun Java API 发送 HTML 电子邮件
【发布时间】:2018-12-05 19:01:33
【问题描述】:

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

到目前为止,我已经验证了我的域,通过 API 成功发送了一封电子邮件,并通过 Java 中的 API 成功发送了一封 HTML(基本)电子邮件。 每当我尝试使用任何电子邮件模板时,我都无法发送电子邮件(通过 API,Java)。我尝试使用此处提供的建议电子邮件模板: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].

堆栈跟踪:

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。虽然它似乎可以与“HTML 版本 whatever 之类的简单 html 一起使用,但它肯定不喜欢任何冗长/“普通”的 html,例如电子邮件模板。

您能否建议任何使用 Java API 的 html 电子邮件的工作示例或有关如何发送 html 并拥有有效 json 的任何提示?

非常感谢

【问题讨论】:

  • 你有什么方法可以检查网络请求吗?也许传出请求是有效的,而您期待(但未收到)JSON 响应?
  • 是的,暂时忽略响应位,确保发送位正常
  • 问题被隔离到 HERE (String) .queryString("html", HERE) 的内容中,好像值是 &lt;html&gt;&lt;strong&gt;whatever&lt;/strong&gt;&lt;/html&gt;,它在任何邮件客户端中以 html 的形式发送和接收。问题仍然是,如何使用 html 页面填充 HERE?刚试过StringEscapeUtils.escapeHtml4(returnEmail())) 还是有同样的问题
  • 如果你正在尝试使用mailgun,我建议你看看this project on GitHub我之前使用过这个项目,它对我发送电子邮件模板很有效。
  • 对于复杂的html,我使用了这个:response= Mail.using(configuration) .from(fromName, fromEmail) .to("To Address") .subject("some subject") .html("Content String With Html Tags") .build() .send();

标签: java html email mailgun unirest


【解决方案1】:

从报错信息来看:

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 文档,看看您是否可以强制使用其他编码类型。

或者,您可以使用问题 cmets 中所述的this other library(免责声明:我是开发人员)。 OP 抱怨 不适用于 here 中提到的复杂 html。我的意思是内容帮助器机制,您可以在其中使用链式方法调用(DSL 样式)构建 HTML 内容。如果您已经拥有 HTML,则只需将其传递给 html() 方法调用,如 cmets 上所述。

你的代码看起来有点像这样:

// 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();
}

【讨论】:

  • 我正在试一试,并得到了这个错误:javax.net.ssl.SSLHandshakeException: sun.security....find valid certificate path to requested target。我缺少什么证书?邮筒?还是我的域?
  • 这确实是正确答案!非常感谢您的工作和努力!
  • 如果有人在让代码工作时遇到问题,请使用@sargue 的库,他提到您需要 Jersey 客户端 (mvnrepository.com/artifact/org.glassfish.jersey.core/…) 但您还需要注入管理器 (@987654325 @) 也是如此。因此,请确保在尝试运行之前安装两者,否则会出现异常。
  • @Silmarilos 仅当您使用 Jersey 版本 >= 2.26 时,该版本已经经历了多次更改 (jersey.github.io/release-notes/2.26.html)。该库依赖于 2.25.1,因此只有在显式 Jersey 依赖项时才会出现这种情况。
【解决方案2】:

我在尝试通过 Unirest.post(...).queryString("html", massStringHere)..asJson(); 发布大型 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 行 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 中配置的允许查询字符串长度。我尝试更改内容以形成 url 编码并使用 .field("html", massStringHere),但这并没有像我预期的那样工作。为什么必须在 URL 中指定 POST 的所有字段是 IMO 的设计缺陷。我还没有找到解决方法,但会尝试这里给出的建议。希望不要求助于 MIME 路线:-/

更新:已确认 https://github.com/sargue/mailgun 是 Mailgun 集成的方法,并且不受显然困扰 Unirest 的 HTML 大小限制的影响。在几分钟内轻松集成。

【讨论】:

    【解决方案3】:

    从您共享的 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 字符串中。

    【讨论】:

    • 那封电子邮件的样式到底如何?
    • 您必须提供内联 css 或在 html 本身中添加
    • 无论如何,这是行不通的。如原始答案中所述,问题在于:如何将 HTML 内容作为字符串 JSON 值发送。从 HTML 中删除不是一个解决方案,因为这些标签很重要并且针对特定的电子邮件客户端
    • 据我了解,所有电子邮件客户端都不会获取外部 css 而不是应用,它需要在
    • 从问题看来,您只需要在 html 中转义双引号。
    猜你喜欢
    • 2022-10-01
    • 2015-03-25
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2017-10-12
    相关资源
    最近更新 更多