【发布时间】:2011-03-09 18:52:42
【问题描述】:
中午我试图让我的应用程序通过 javamail 发送 html+图像,我只设法发送 html,但图像我遇到了一些问题。我决定创建一个多部分消息,一切正常,但随后我使用类加载器从 WEB-INF/resources/images 中检索 .png 文件,我得到一个 NullPointerExcetion,我不知道这是为什么?
这是我的 EJB(3.0) 的样子。我很感激这个我对 ClassLoader 类没有太多经验的人(不太了解它)。
@Stateless(name = "ejbs/EmailServiceEJB")
public class EmailServiceEJB implements IEmailServiceEJB {
@Resource(name = "mail/myMailSession")
private Session mailSession;
public void sendAccountActivationLinkToBuyer(String destinationEmail,
String name) {
// Destination of the email
String to = destinationEmail;
String from = "dontreply2thismessage@gmail.com";
try {
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";
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
if (classLoader == null) {
classLoader = this.getClass().getClassLoader();
if (classLoader == null) {
System.out.println("IT IS NULL AGAIN!!!!");
}
}
DataSource ds = new URLDataSource(classLoader.getResource(fileName));
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);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
我想提一下,我正在将 JEE6 与 glassfishV3 一起使用,我不知道我的方法是否与此应用程序服务器兼容。
更新 当我将上面的代码修改为
String fileName = "logoemailtemplate.png";
我收到一封电子邮件,它有效。
但现在我没有收到短信。 :) 有什么错误吗?
【问题讨论】:
-
您的代码不明确。您实例化了一个流,但没有在数据源中使用它。
-
你说得对,流不应该在那里,它属于我以前使用的旧代码。需要进行一些重构。感谢您的建议。
标签: java jakarta-ee glassfish ejb-3.0 jakarta-mail