springmail sample

classic Classic list List threaded Threaded
6 messages Options
Reply | Threaded
Open this post in threaded view
|

springmail sample

omaroman
Rich HTML email in Spring with Thymeleaf
http://www.thymeleaf.org/springmail.html

The sample doesn't work, it throws this exception

ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][2] Exception processing template "email-simple.html": Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]

Anybody knows how to fix it?
Reply | Threaded
Open this post in threaded view
|

Re: springmail sample

danielfernandez
Administrator
It works OK for me...

Are you using the source .zip code that can be downloaded from http://www.thymeleaf.org/documentation.html ? Is there anything you have changed there? How are you deploying and running it --what webserver, etc--?

For me, just modifying the "src/main/resources/configuration.properties" file for setting up email server authentication and executing "mvn clean compile tomcat:run" works perfectly...

Also, could you send a complete exception trace instead of just the last line?

Regards,
Daniel.
Reply | Threaded
Open this post in threaded view
|

Re: springmail sample

omaroman
Hello,

These are the steps I did:

- I downloaded the source code from
- I created a new project in IntelliJ 11 and copy the source code into it.
- I deployed the app into Jetty 8.1.1

This is the output directly from IntelliJ

/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -DSTOP.PORT=0 -Dcom.sun.management.jmxremote= -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -DOPTIONS=jmx -Didea.launcher.port=7533 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 11.app/bin" -Dfile.encoding=MacRoman -classpath "start.jar:/Applications/IntelliJ IDEA 11.app/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain org.eclipse.jetty.start.Main /private/var/folders/gx/ydxckc414kn1cnsbtc3j9tvh0000gn/T/context2598028065078726582config/contexts-config.xml
[2012-04-28 12:38:36,449] Artifact springmail:war exploded: Server is not connected. Press 'Deploy' to start deployment.
50443
STOP.KEY=1tyvokx33japs
2012-04-28 12:38:40.453:WARN:oejd.ContextDeployer:ContextDeployer is deprecated. Use ContextProvider
2012-04-28 12:38:40.462:INFO:oejs.Server:jetty-8.1.1.v20120215
2012-04-28 12:38:40.680:INFO:oejdp.ScanningAppProvider:Deployment monitor /Volumes/PRO/Java/NLR/jetty-hightide-8.1.1.v20120215/webapps at interval 1
2012-04-28 12:38:40.683:INFO:oejdp.ScanningAppProvider:Deployment monitor /Volumes/PRO/Java/NLR/jetty-hightide-8.1.1.v20120215/contexts at interval 1
2012-04-28 12:38:40.759:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:8080
2012-04-28 12:38:40.759:INFO:oejs.Server:jetty-8.1.1.v20120215
Connected to server
[2012-04-28 12:38:41,187] Artifact springmail:war exploded: Artifact is being deployed, please wait...
2012-04-28 12:38:42.831:INFO:oejd.ContextDeployer:Deploy /private/var/folders/gx/ydxckc414kn1cnsbtc3j9tvh0000gn/T/context4422749122354782967deploy/springmail.xml -> o.e.j.w.WebAppContext{/springmail,file:/Volumes/PRO/Java/NLR/springmail/out/artifacts/springmail/}
2012-04-28 12:38:47.565:WARN:oejj.ObjectMBean:No mbean getter or setters found for maxCookieAge in class org.eclipse.jetty.server.session.HashSessionManager
2012-04-28 12:38:47.566:WARN:oejj.ObjectMBean:No mbean getter or setters found for sessionPath in class org.eclipse.jetty.server.session.HashSessionManager
2012-04-28 12:38:47.606:INFO:/springmail:No Spring WebApplicationInitializer types detected on classpath
2012-04-28 12:38:48.611:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/springmail,file:/Volumes/PRO/Java/NLR/springmail/out/artifacts/springmail/}
2012-04-28 12:38:48.611:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/springmail,file:/Volumes/PRO/Java/NLR/springmail/out/artifacts/springmail/}
2012-04-28 12:38:48.611:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/springmail,file:/Volumes/PRO/Java/NLR/springmail/out/artifacts/springmail/}
2012-04-28 12:38:48.964:INFO:/springmail:Initializing Spring FrameworkServlet 'spring'
0    [Scanner-2] INFO  org.springframework.web.servlet.DispatcherServlet  - FrameworkServlet 'spring': initialization started
33   [Scanner-2] INFO  org.springframework.web.context.support.XmlWebApplicationContext  - Refreshing WebApplicationContext for namespace 'spring-servlet': startup date [Sat Apr 28 12:38:48 CDT 2012]; root of context hierarchy
80   [Scanner-2] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-servlet.xml]
374  [Scanner-2] INFO  org.springframework.context.annotation.ClassPathBeanDefinitionScanner  - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
566  [Scanner-2] INFO  org.springframework.beans.factory.config.PropertyPlaceholderConfigurer  - Loading properties file from class path resource [resources/configuration.properties]
591  [Scanner-2] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory  - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6b1ce2ad: defining beans [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,emailService,mainController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,multipartResolver,mailSender,emailTemplateResolver,webTemplateResolver,templateEngine,viewResolver,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
694  [Scanner-2] INFO  org.springframework.web.servlet.handler.SimpleUrlHandlerMapping  - Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
850  [Scanner-2] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  - Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String thymeleafexamples.springmail.web.MainController.root()
851  [Scanner-2] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  - Mapped "{[/index.html],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String thymeleafexamples.springmail.web.MainController.index()
852  [Scanner-2] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  - Mapped "{[/sendMailWithAttachment],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String thymeleafexamples.springmail.web.MainController.sendMailWithAttachment(java.lang.String,java.lang.String,org.springframework.web.multipart.MultipartFile,java.util.Locale) throws javax.mail.MessagingException,java.io.IOException
852  [Scanner-2] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  - Mapped "{[/sendMailWithInlineImage],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String thymeleafexamples.springmail.web.MainController.sendMailWithInline(java.lang.String,java.lang.String,org.springframework.web.multipart.MultipartFile,java.util.Locale) throws javax.mail.MessagingException,java.io.IOException
852  [Scanner-2] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  - Mapped "{[/sent.html],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String thymeleafexamples.springmail.web.MainController.sent()
852  [Scanner-2] INFO  org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  - Mapped "{[/sendMailSimple],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String thymeleafexamples.springmail.web.MainController.sendTextMail(javax.servlet.http.HttpServletRequest,java.lang.String,java.lang.String,java.util.Locale) throws javax.mail.MessagingException
1294 [Scanner-2] INFO  org.springframework.beans.factory.config.PropertiesFactoryBean  - Loading properties file from class path resource [resources/javamail.properties]
1581 [Scanner-2] INFO  org.springframework.web.servlet.DispatcherServlet  - FrameworkServlet 'spring': initialization completed in 1579 ms
[2012-04-28 12:38:50,864] Artifact springmail:war exploded: Artifact is deployed successfully
1068 [qtp1543085802-36] INFO org.thymeleaf.TemplateEngine - [THYMELEAF] INITIALIZING TEMPLATE ENGINE
1118 [qtp1543085802-36] INFO org.thymeleaf.templateresolver.AbstractTemplateResolver - [THYMELEAF] INITIALIZING TEMPLATE RESOLVER: org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
1118 [qtp1543085802-36] INFO org.thymeleaf.templateresolver.AbstractTemplateResolver - [THYMELEAF] TEMPLATE RESOLVER INITIALIZED OK
1118 [qtp1543085802-36] INFO org.thymeleaf.templateresolver.AbstractTemplateResolver - [THYMELEAF] INITIALIZING TEMPLATE RESOLVER: org.thymeleaf.templateresolver.ServletContextTemplateResolver
1118 [qtp1543085802-36] INFO org.thymeleaf.templateresolver.AbstractTemplateResolver - [THYMELEAF] TEMPLATE RESOLVER INITIALIZED OK
1119 [qtp1543085802-36] INFO org.thymeleaf.messageresolver.AbstractMessageResolver - [THYMELEAF] INITIALIZING MESSAGE RESOLVER: org.thymeleaf.spring3.messageresolver.SpringMessageResolver
1119 [qtp1543085802-36] INFO org.thymeleaf.messageresolver.AbstractMessageResolver - [THYMELEAF] MESSAGE RESOLVER INITIALIZED OK
1124 [qtp1543085802-36] INFO org.thymeleaf.TemplateEngine.CONFIG - [THYMELEAF] TEMPLATE ENGINE CONFIGURATION:
[THYMELEAF] * Cache Factory implementation: org.thymeleaf.cache.StandardCacheManager
[THYMELEAF] * Template modes:
[THYMELEAF]     * LEGACYHTML5
[THYMELEAF]     * HTML5
[THYMELEAF]     * VALIDXML
[THYMELEAF]     * XML
[THYMELEAF]     * VALIDXHTML
[THYMELEAF]     * XHTML
[THYMELEAF] * Template resolvers (in order):
[THYMELEAF]     * [1] org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
[THYMELEAF]     * [2] org.thymeleaf.templateresolver.ServletContextTemplateResolver
[THYMELEAF] * Message resolvers (in order):
[THYMELEAF]     * org.thymeleaf.spring3.messageresolver.SpringMessageResolver
[THYMELEAF] * Dialect: org.thymeleaf.spring3.dialect.SpringStandardDialect
[THYMELEAF]     * Prefix: "th"
[THYMELEAF] TEMPLATE ENGINE CONFIGURED OK
1124 [qtp1543085802-36] INFO org.thymeleaf.TemplateEngine - [THYMELEAF] TEMPLATE ENGINE INITIALIZED
16955 [qtp1543085802-34] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][2] Exception processing template "email-simple.html": Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]


BTW, Thymeleaf is such a great project!

Best regards
Omar O. Román
Reply | Threaded
Open this post in threaded view
|

Re: springmail sample

danielfernandez
Administrator
OK. Your project is not being correctly deployed. Specifically, it seems that the resources at src/main/resources/mail folder are not being correctly copied to WEB-INF/classes, as they should per the Maven configuration at the pom.xml file.

This causes the first template resolver, the ClassLoaderTemplateResolver, not to find the email templates, and therefore passes control on to the second template resolver, a ServletContextTemplateResolver, who outputs that error because it isn't meant to resolve the email templates (that's a task of the ClassLoader one).

It seems something is wrong in your deployment procedure. I cannot know whether you should put the blame on IDEA, on its maven integration plugin, or on jetty...

Regards,
Daniel.
Reply | Threaded
Open this post in threaded view
|

Re: springmail sample

danielfernandez
Administrator
Additional info: I've just tested this on jetty (without IDEA, which I don't use...yet) using the jetty plugin for maven, and it works OK.

For this, I just added this to the project's pom.xml file:

<plugin>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>jetty-maven-plugin</artifactId>
</plugin>

And then run from the command line:

mvn clean compile jetty:run

The application started at http://localhost:8080 and sending email worked OK.

So your problem looks more IDEA-related than jetty-caused.

Regards,
Daniel.
Reply | Threaded
Open this post in threaded view
|

Re: springmail sample

omaroman
Thanks for your quick reply.

Since I could not run the Springmail app per se, I overloaded the sendSimpleMail in the EmailService class:

public void sendSimpleMail(HttpServletRequest request,
            final String recipientName, final String recipientEmail, final Locale locale)
            throws MessagingException {

        // Prepare the evaluation context
        final WebContext ctx = new WebContext(request, request.getServletContext(), locale); // new Locale("en")
        ctx.setVariable("name", recipientName);
        ctx.setVariable("subscriptionDate", new Date());
        ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));

        // Prepare message using a Spring helper
        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject("Example HTML email (simple)");
        message.setFrom("thymeleaf@example.com");
        message.setTo(recipientEmail);

        // Create the HTML body using Thymeleaf
        final String htmlContent = this.templateEngine.process("email-simple.html", ctx);
        message.setText(htmlContent, true /* isHtml */);

        // Send email
        this.mailSender.send(mimeMessage);
    }


And I invoke it this way:

/*
     * Send HTML mail (simple)
     */
    @RequestMapping(value = "/sendMailSimple", method = RequestMethod.POST)
    public String sendTextMail(HttpServletRequest request,
            @RequestParam("recipientName") final String recipientName,
            @RequestParam("recipientEmail") final String recipientEmail,
            final Locale locale)
            throws MessagingException {

        this.emailService.sendSimpleMail(request, recipientName, recipientEmail, locale);
        return "redirect:sent.html";
       
    }

And I moved the templates to WEB-INF/templates

This way, it worked out running it from IntelliJ and deployed into Jetty.

I suggest you to include the overloaded method.

Thanks for helping me.

Omar O. Román