javamail добавление изображений в электронные письма html. Как?
Я отправляю электронные письма с javamail без проблем (я использую EJB 3.0), проблема в том, когда я пытаюсь добавить изображение в HTML, используя многоэлементный подход. По какой-то причине я получаю FileNotFoundException. Я не знаю, как получить путь к изображению.png, которое находится в WEB-INF/resources/images.
Вот что я сделал:
Message message = new MimeMessage(mailSession);
// From: is our service
message.setFrom(new InternetAddress(from));
// To: destination given
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Uspijesna registracija");
// How to found at http://www.rgagnon.com/javadetails/java-0321.html
message.setContent(generateActivationLinkTemplate(), "text/html");
Date timeStamp = new Date();
message.setSentDate(timeStamp);
// Prepare a multipart HTML
Multipart multipart = new MimeMultipart("related");
// Prepare the HTML
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(generateActivationLinkTemplate(), "text/html");
multipart.addBodyPart(htmlPart);
// PREPARE THE IMAGE
BodyPart imgPart = new MimeBodyPart();
DataSource ds = new FileDataSource("logomailtemplate.png");
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", "the-img-1");
multipart.addBodyPart(imgPart);
// Set the message content!
message.setContent(multipart);
Transport.send(message);
Текст исходит из другого метода, который работает правильно. Я думаю, что проблема в этой строке кода:
DataSource ds = new FileDataSource ("logomailtemplate.png");
Вот что говорит консоль:
java.io.FileNotFoundException: logomailtemplate.png (система не может найти указанный файл)
Как я могу получить доступ к этому изображению? Он находится в WEB-INF/resources/images. Я застрял в день ожидания с этим плохо оцениваю руку:)
-----------------------------------ОБНОВИТЬ-------------- -----------------
Message message = new MimeMessage(mailSession);
// From: is our service
message.setFrom(new InternetAddress(from));
// To: destination given
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Uspijesna registracija");
// How to found at http://www.rgagnon.com/javadetails/java-0321.html
message.setContent(generateActivationLinkTemplate(), "text/html");
Date timeStamp = new Date();
message.setSentDate(timeStamp);
// Prepare a multipart HTML
Multipart multipart = new MimeMultipart();
// Prepare the HTML
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(generateActivationLinkTemplate(), "text/html");
multipart.addBodyPart(htmlPart);
// PREPARE THE IMAGE
BodyPart imgPart = new MimeBodyPart();
String fileName = "WEB-INF/resources/images/logoemailtemplate.png";
InputStream stream = null;
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
stream = classLoader.getResourceAsStream(fileName);
DataSource ds = new ByteArrayDataSource(stream, "image/*");
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", "the-img-1");
multipart.addBodyPart(imgPart);
// Set the message content!
message.setContent(multipart);
Transport.send(message);
------------------------------------------ТРАССИРОВКИ СТЕКА------ -----------------------------
ПРЕДУПРЕЖДЕНИЕ: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() для сервлета Faces Servlet вызвал исключение javax.faces.el.EvaluationException: javax.ejb.EJBException................
SEEVE: javax.ejb.EJBException ActionListenerImpl.java:102) на сайте javax.faces.component.UICommand.broadcast (UICommand.java:315) на сайте javax.faces.component.UIViewRoot.broadcastEvents (UIViewRoot.java:775) на сайте javax.faces.component.UIViewPot. (UIViewRoot.java:1267) на com.sun.faces.lifecycle.InvokeApplicationPhase.execute (InvokeApplicationPhase.java:82) на com.sun.faces.lifecycle.Phase.doPhase (Phase.java:101) на com.sun. faces.lifecycle.LifecycleImpl.execute (LifecycleImpl.java:118) в javax.faces.webapp.FacesServlet.service (FacesServlet.java:312) в org.apache.catalina.core.StandardWrapper.service (StandardWrapper.java:15) в org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java:279) в org.apache.catalina.core.Standard ContextValve.invoke (StandardContextValve.java:188) на org.apache.catalina.core.StandardPipeline.invoke (StandardPipeline.java:641) на com.sun.enterprise.web.WebPipeline.invoke (WebPipeline.java:97) на com.sun.enterprise.web..java: 325) по адресу org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:226) по адресу com.sun.enterprise.v3.services.impl.ContainerMapper.service (ContainerMapper.java:165) по адресу com. sun.grizzly.http.ProcessorTask.invokeAdapter (ProcessorTask.java:791) в com.sun.grizzly.http.ProcessorTask.doProcess (ProcessorTask.java:693) в com.sun.grizzly.http.ProcessorTask.processor (Java: 954) на com.sun.grizzly.http.DefaultProtocolFilter.execute (DefaultProtocolFilter.java:170) на com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter (DefaultProtocolChain.java:135) в com.sun.grizzly.DefaultProtocolChain.execute (DefaultProtocolChain.java:102) в com.sun.grizzly.DefaultProtocolChain.execute (DefaultProtocolChain.java:88) в com.sun.grizzly.http.Htp..execute (HttpProtocolChain.java:76) по адресу com.sun.grizzly.ProtocolChainContextTask.doCall (ProtocolChainContextTask.java:53) по адресу com.sun.grizzly.SelectionKeyContextTask.call (SelectionKeyContextTaszz.sun.un.un.jpg). ContextTask.run (ContextTask.java:69) в com.sun.grizzly.util.AbstractThreadPool $ Worker.doWork (AbstractThreadPool.java:330) в com.sun.grizzly.util.AbstractThreadPool $ Worker.run (AbstractThreadPool.java: 309) в java.lang.Thread.run (Thread.java:662), вызванный: javax.ejb.EJBException в com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5119) в com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5017) на com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4805) на com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2004) на com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1955) на com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBjococH) по адресу com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84) по адресу $Proxy162.sendAccountActivationLinkToBuyer(Неизвестный источник Собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) в sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) в java.vo.egn.hog () в com.sun.el.parser.AstValue.invoke(AstValue.java:234) в com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297) в org.jboss.weld.util.el.ForwardingMethodkepression (ForwardingMethodExpression.java:43) в org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:72) в com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98) в jav.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) ... еще 32
Вызывается: sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) в sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) в java.lang.red.j.g.g.jg.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1056) при org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1128) при com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5292) на com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:615) на com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(interavaor): 7) ejb.EjbInvocation.proceed(EjbInvocation.java:567) в org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:47) в sun.reflect.NativeMethodAccessorImpl.invoke0(собственный метод) в sun.reflect.NativeMethodAccessorImpl.Imphoj вызвать (DelegatingMethodAccessorImpl.java:25) в java.lang.reflect.Method.invoke(Method.java:597) в com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858) в com.sun.ejb.containers.interceptors..java:157) в com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:139) в sun.reflect.NativeMethodAccessorImpl.invoke0(собственный метод) в sun.reflect.NativeMethoor: 39) на солнце.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) в java.lang.reflect.Method.invoke(Method.java:597) в com.sun.ejb.containers.interceptors.AroundInvokeInterceptor: atan com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797) в com.sun.ejb.containers.interceptors.InceptceptManager.intercept(InterceptorManager.java:367) в com.sunersej.BaseContainer.__intercept(BaseContainer.java:5264) в com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5252) в com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObet.jj). Еще 45
----------------------------------- ОБНОВЛЕНИЕ 2 ------------- ----------------------------
String fileName = "/WEB-INF/resources/images/logoemailtemplate.png";
InputStream stream = null;
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
//This line dont work!
stream = classLoader.getResourceAsStream(fileName);
DataSource ds = new URLDataSource(classLoader.getResource(fileName));
// DataSource ds = new FileDataSource (новый файл (classLoader // .getResource(fileName).toURI())); Также не работает. Также я попробовал как / и без /
1 ответ
Одним из способов достижения этого может быть:
DataSource ds = new ByteArrayDataSource(getServletContext().getResourceAsStream("WEB-INF/resources/images/logomailtemplate.png") ,mimeType);
getServletContext().getResourceAsStream()
получен от HttpServlet
и возвращает InputStream
,
Еще лучше сделать это
String fileName = "/WEB-INF/resources/images/logomailtemplate.png";
InputStream stream = getServletContext().getResourceAsStream(fileName); //or null if you can't obtain a ServletContext
if (stream == null) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
stream = classLoader.getResourceAsStream(fileName);
}
DataSource ds = new ByteArrayDataSource(stream, "image/*");
Обновить
альтернативно
String fileName = "WEB-INF/resources/images/logomailtemplate.png";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
}
DataSource ds = new FileDataSource(new File(classLoader.getResource(fileName).toURI()));
//OR
DataSource ds = new URLDataSource(classLoader.getResource(fileName));
Убедитесь, что ваш fileName
начинается с "/".