Это мой код для отправки почты пользователю с помощью javax.mail.1.5.2. Мне нужно прикрепить некоторые изображения. Для этого я использовал servetcontext getRealPath. Но он говорит, что переменная сервлета ServletContextEvent (см. Код) должна быть инициализирована. Есть что-то, чего не хватает. Вот мой код.Ошибка при встраивании изображений в почту через javamail
public void sendSSLMessage(String recipients[], String subject,
String htmlText, String from , MailSSLSocketFactory sf) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication
getPasswordAuthentication() {
return new
PasswordAuthentication("[email protected]", "[email protected]$");
}
});
session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
/*Message msg = new MimeMessage(session);*/
InternetAddress addressFrom = new InternetAddress(from);
message.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, addressTo);
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlText, "text/html");
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
ServletContextEvent sce;
ServletContext context = sce.getServletContext(); //this shows error. sce may not have been initialized
String contextPath = context.getRealPath("/");
//...
File contextDir = new File(contextPath);
File emailImage = new File(contextDir, "img/logo.png");
DataSource fds = new FileDataSource(emailImage);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<logo>");
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
// Setting the Subject and Content Type
message.setSubject(subject);
Transport.send(message);
}