我是jsp的新手,我正在尝试从jsp页面发送电子邮件,但它没有任何堆栈跟踪就失败了。这是我试过的代码,
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%
//username for abc@gmail.com will be "abc"
String username = "abc";
String password = "password";
String result = null;
try {
Properties props = System.getProperties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session emailSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("sender_username","sender_password");
}
});
emailSession.setDebug(true);
Message message = new MimeMessage(emailSession);
message.setFrom(new InternetAddress(
"sender_username@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("test123@gmail.com"));
message.setSubject("Test mail from Java");
message.setText("Hello. this is a test");
Transport transport = emailSession.getTransport("smtps");
transport.connect("smtp.gmail.com", username, password);
transport.sendMessage(message, message.getAllRecipients());
result = "Successfully sent email";
} catch (MessagingException e) {
result = "Unable to send email";
e.printStackTrace();
}
%>
<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>
&#13;
我是从博客/教程页面上看到的。由于它没有打印堆栈跟踪,我也无法看到它的失败位置。它失败了 &#34;结果:无法发送电子邮件&#34;
答案 0 :(得分:0)
final String username = "chandrasekar@gmail.com";//from which you want to send mail
final String password = "chandra@123";//password off your mail id
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);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("chandrasekar@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("etc@gmail.com"));//whom you want to send mail
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}