这是我使用javax.mail.1.5.2向用户发送邮件的代码。我需要附上一些图片。为此,我使用了servetcontext getRealPath。但是它说ServletContextEvent变量sce(参见代码)需要初始化。有一些东西是缺失的。这是我的代码。
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("support@jiffie.in", "support@1234$");
}
});
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);
}
答案 0 :(得分:0)
首先,修复所有这些common JavaMail mistakes来清理代码。
sce只会出现在你的程序中间,而不会被分配一个值,这就是为什么它抱怨没有被初始化。但实际上,如果你只是想要ServletContext,那就去掉sce并使用javax.servlet.ServletRequest方法getServletContext()。但是你需要从你调用这个方法的Servlet中传入“request”对象。