如何配置用于JavaMail的邮件服务器?

我正在尝试使用以下代码:

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import javax.mail.*; import javax.mail.internet.*; // important import javax.mail.event.*; // important import java.net.*; import java.util.*; public class servletmail extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); response.setContentType("text/html"); try { Properties props=new Properties(); props.put("mail.smtp.host","localhost"); // 'localhost' for testing Session session1 = Session.getDefaultInstance(props,null); String s1 = request.getParameter("text1"); //sender (from) String s2 = request.getParameter("text2"); String s3 = request.getParameter("text3"); String s4 = request.getParameter("area1"); Message message =new MimeMessage(session1); message.setFrom(new InternetAddress(s1)); message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(s2,false)); message.setSubject(s3); message.setText(s4); Transport.send(message); out.println("mail has been sent"); } catch(Exception ex) { System.out.println("ERROR....."+ex); } } } 

我正在使用mail.jar和activation.jar。 但我无法理解如何配置邮件服务器。 我应该使用哪个邮件服务器? 我可以使用上面的代码发送电子邮件吗? 邮件服务器有什么要求? 我该如何配置?

首先,您需要一个SMTP服务器 。 它需要能够发送电子邮件。 与您需要HTTP服务器以便能够为网站服务的方式相同。 您显然已经有一个HTTP服务器(带有servletcontainer),但您还没有配置SMTP服务器。

您可以使用与您自己的现有电子邮件帐户关联的SMTP服务器,例如来自ISP或Gmail,Yahoo等公共邮箱的SMTP服务器。您可以在其文档中找到SMTP连接详细信息。 您通常只需要知道主机名端口号用户名/密码与您的电子邮件帐户的用户名/密码相同。

然后,应将主机名和端口号设置为JavaMail的SMTP属性:

 Properties properties = new Properties(); properties.put("mail.transport.protocol", "smtp"); properties.put("mail.smtp.host", "smtp.example.com"); // smtp.gmail.com? properties.put("mail.smtp.port", "25"); 

用户名/密码应在Authenticator ,如下所示:

 properties.put("mail.smtp.auth", "true"); Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("yourusername", "yourpassword"); } }; 

然后您可以按如下方式获取邮件会话:

 Session session = Session.getDefaultInstance(properties, authenticator); 

但是,使用您的ISP或公共邮箱的帐户,您只能在电子邮件的“ From字段中使用您自己的地址,并且通常也会限制您在特定时间间隔内发送的电子邮件数量。 如果你想解决这个问题,那么你需要安装自己的SMTP服务器,例如Apache James ,它是基于Java的,或者是Microsoft Exchange等。

毕竟,我建议您通过JavaMail教程,以便更好地理解。