我想在执行给定的jsp页面时发送邮件。我已经包含了javamail jar文件和java激活框架jar文件。但是这段代码给出的错误是没有指定密码,而我提供了正确的密码,如下面的代码所示。任何帮助将非常感谢!完全不熟悉JSP。
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ page import = "java.io.*,java.util.*,javax.mail.*"%>
<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%
String result;
// Recipient's email ID needs to be mentioned.
String to = "xzu@gmail.com";
// Sender's email ID needs to be mentioned
String from = "xzu@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties object
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.user", "xzu@gmail.com");
properties.setProperty("mail.password", "xzu");
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session mailSession = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = mex.getMessage();
}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align = "center">
<%
out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>
答案 0 :(得分:0)
我假设您的计算机上没有运行邮件服务器而您尝试使用Google发送电子邮件...
然后host = localhost错了。
要做到这一点,你需要像:
final String username = "xyz@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
然后创建一个会话
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
然后通过以下方式发送您的电子邮件:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(messageText);
Transport.send(message);