gpt4 book ai didi

tomcat - 如果我尝试使用 servlet 发送电子邮件,为什么无法解析本地主机

转载 作者:行者123 更新时间:2023-11-28 22:56:33 25 4
gpt4 key购买 nike

我有属性文件 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);
}

如何解析属性文件中的本地主机,但在我的 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");

没用!!!...有谁知道为什么吗?

最佳答案

文件操作需要来自 servlet 的完整路径。假设您的 /config/ 文件夹在您的网络应用程序的路径下,您需要使用 application.getRealPath("/") [在 JSP 中] 或 context .getRealPath("/") 在 servlet 中,但首先您必须在 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");

关于tomcat - 如果我尝试使用 servlet 发送电子邮件,为什么无法解析本地主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25875288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com