如果我尝试使用servlet发送电子邮件,无法解析localhost的原因

时间:2014-09-16 17:44:46

标签: tomcat servlets properties-file

我有属性文件js.smtp.properties:

mail.sender.host=localhost
mail.sender.username=
mail.sender.password=
mail.sender.from=info@mycompany.com
mail.sender.protocol=smtp
mail.sender.port=31

我的java类看起来像这样:

      ...


FileInputStream smtpfis = new FileInputStream("/home/webserver/tomcat6/properties/js.smtp.properties");
        smtpProp.load(smtpfis);

public void sendEmail(String recepientAdress, String userID, String randNum) throws AddressException, MessagingException, UnsupportedEncodingException
    {

        String from = smtpProp.getProperty("mail.sender.from");     
        String host = smtpProp.getProperty("mail.sender.host");
        String port = smtpProp.getProperty("mail.sender.port");
        String subject = "Password Change Notification";

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", host);

        Session session = Session.getInstance(properties);

        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(from));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recepientAdress));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        msg.setContent("<p>Hi there,</p><br /><a>We received a request to reset your password. <br />To reset your password and access your account, click the link below.</a><br />"
        + "<a href=\"http://" + "devserver.myapplication.com" + ":8080/" + directoryName +"/ConfirmedResetPasswordPage.jsp?randNum=" + randNum + "&practiceName=" + practiceName + "\"> Click Here </a>"        
        , "text/html; charset=utf-8" );

        Transport.send(msg);
    }

如何解决属性文件中的localhost已解决但在我的msg.setContent()中我无法使其工作,而是必须提供整个服务器名称???

我做错了吗?

另外,如果我打开tomcat管理器,我可以打开这些属性文件并通过输入以下内容查看内容:

devserver.myapplication.com:8080/config/js.smtp.properties

但是如果我尝试更改这行代码:

FileInputStream smtpfis = new FileInputStream("/home/webserver/tomcat6/properties/js.smtp.properties");

为:

FileInputStream smtpfis = new FileInputStream("/config/js.smtp.properties");

它不起作用!!! ... 有谁知道为什么?

1 个答案:

答案 0 :(得分:1)

文件操作需要来自servlet内部的完整路径。假设您的/config/文件夹位于Web应用程序的路径下,您需要在servlet中使用application.getRealPath("/") [在JSP中]或context.getRealPath("/"),但首先必须在servlet中使用上下文init方法:

private ServletContext context;

public void init(ServletConfig config) throws ServletException
{
    this.context = config.getServletContext();
}
...
...
FileInputStream smtpfis = new FileInputStream(context.getRealPath("/") + "/config/js.smtp.properties");

如果config是您的网络应用程序所在的文件夹:

FileInputStream smtpfis = new FileInputStream(context.getRealPath("/") + "/js.smtp.properties");