我一直在尝试使用jsp和servlets NetBeans发送邮件。我尝试了很多代码,但运行项目时出现了常见的404状态错误。我使用glassfish服务器3.以下是我的代码。
的index.jsp:
<form action="sendmail">
Sending Id :<input type="text" name="semail" />
Title:<input type="text" name="title" />
Message :</td><td><textarea rows="5" cols="30" name="msg"></textarea>
<input type="submit" name="submit" value="mail" />
</table>
</form>
sendmail.java:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.mail.*;
import javax.mail.internet.*;
public class sendmail extends HttpServlet
{
String username ="//some username";
String password = "//some password";
String smtphost = "smtp.gmail.com";
String compression = "";
String from = "abc@gmail.com";
String to = "";
String body = "";
Transport tr = null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String semail = request.getParameter("semail");
String title = request.getParameter("title");
String msg2 = request.getParameter("msg");
to=semail;
compression=title;
body=msg2;
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
// Get a Session object
Session mailSession = Session.getDefaultInstance(props, null);
// construct the message
Message msg = new MimeMessage(mailSession);
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(compression);
msg.setText(body);
msg.setSentDate(new Date());
tr = mailSession.getTransport("smtp");
tr.connect(smtphost, username, password);
msg.saveChanges();
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
out.print("<script>alert('Mail has been sent successfully......');</script>");
response.sendRedirect("success.jsp");
}
catch (Exception e)
{
response.sendRedirect("fail.jsp");
} finally {
out.close();
}
}
}
success.jsp和fail.jsp将分别显示单词success和failed。
请帮助解决错误!提前谢谢。