2010-09-21 60 views
7

如何从JSP/servlet发送电子邮件?是否需要下载一些jar文件,或者您是否可以从JSP/servlet发送一封没有任何jar文件的电子邮件?如何从jsp/servlet发送电子邮件?

  • 我的Java代码是什么样的?

  • 我的HTML代码看起来像什么(如果有的话)?

  • 需要多个类,还是只能使用一个类?

+7

请在google上发布这样的小问题,然后再发布到SO上。以下链接是前10个结果之一。 – 2010-09-21 07:34:33

+4

谷歌必然会受欢迎的结果。人们使用StackOverflow获得实际的人意见,而不是Mountain View算法。这是StackOverflow恕我直言的整点。 – MonoThreaded 2012-08-04 09:45:06

+0

越来越元,这就是积分制的要点。良好的Q/A获得更多的积分,在搜索中显示更多......但是,是的,更好的结果(希望)。类似的想法,以页面排名,寿。 – Thufir 2013-12-23 13:41:24

回答

2

我使用JavaMail包和它的作品非常好。上面显示的示例是好的,但正如我所看到的,他们没有在外部文件中定义参数(例如web.xml),这是建议的...

想象一下,您要更改您的电子邮件地址或SMTP主机。 。编辑web.xml文件比使用邮件功能的servlet要容易得多。例如添加下一行web.xml中

<context-param> 
<param-name>smtp_server</param-name> 
<param-value>smtp.blabla.com</param-value></context-param> 

然后你就可以从servlet的访问这些参数与

// 1 - init 
    Properties props = new Properties(); 
    //props.put("mail.transport.protocol", "smtp"); 
    props.put("mail.smtp.host", smtp_server); 
    props.put("mail.smtp.port", smtp_port); 
21

寄件人逻辑在其自己的独立的类应该去,你可以重复使用无处不在。 JSP文件只能包含表示逻辑和标记。 Servlet类应该以恰当的方式处理请求并调用邮件程序类。这里有您需要采取的步骤:

  1. 首先决定你想使用,这样你就可以发送电子邮件这SMTP server。你的ISP之一? Gmail之一?雅虎?网站托管提供商?一个自我维护的?无论如何,请指出此SMTP服务器的主机名,端口,用户名和密码。你将需要这些信息。


  2. 创建一个使用JavaMail API发送邮件一个普通的Java类。 JavaMail API附带优秀的tutorialFAQ。命名类Mailer并给它一个send()方法(或任何你想要的)。使用一些测试类与main()方法是这样进行测试:

    public class TestMail { 
        public static void main(String... args) throws Exception { 
         // Create mailer. 
         String hostname = "smtp.example.com"; 
         int port = 2525; 
         String username = "nobody"; 
         String password = "idonttellyou"; 
         Mailer mailer = new Mailer(hostname, port, username, password); 
    
         // Send mail. 
         String from = "[email protected]"; 
         String to = "[email protected]"; 
         String subject = "Interesting news"; 
         String message = "I've got JavaMail to work!"; 
         mailer.send(from, to, subject, message); 
        } 
    } 
    

    你可以把它简单或先进的,只要你想。没关系,只要你有一个类可以发送这样的邮件。


  3. 现在JSP的一部分,它不是完全清楚为什么你提到的JSP,但是由于JSP是supposed只代表HTML,我敢打赌,你想有像在JSP联络表格。这里有一个开创性的例子:

    <form action="contact" method="post"> 
        <p>Your email address: <input name="email"></p> 
        <p>Mail subject: <input name="subject"></p> 
        <p>Mail message: <textarea name="message"></textarea></p> 
        <p><input type="submit"><span class="message">${message}</span></p> 
    </form> 
    

    是的,很简单,只需标记/风格它任何你想要的方式。


  4. 现在,创建一个Servlet类侦听的/contact一个url-pattern(相同的形式被提交给)和实施doPost()方法(相同的方法,使用的形式)如下:

    public class ContactServlet extends HttpServlet { 
        private Mailer mailer; 
        private String to; 
    
        public void init() { 
         // Create mailer. You could eventually obtain the settings as 
         // web.xml init parameters or from some properties file. 
         String hostname = "smtp.example.com"; 
         int port = 2525; 
         String username = "nobody"; 
         String password = "forgetit"; 
         this.mailer = new Mailer(hostname, port, username, password); 
         this.to = "[email protected]"; 
        } 
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
         String email = request.getParameter("email"); 
         String subject = request.getParameter("subject"); 
         String message = request.getParameter("message"); 
         // Do some validations and then send mail: 
    
         try { 
          mailer.send(email, to, subject, message); 
          request.setAttribute("message", "Mail succesfully sent!"); 
          request.getRequestDispatcher("/WEB-INF/contact.jsp").forward(request, response); 
         } catch (MailException e) { 
          throw new ServletException("Mailer failed", e); 
         } 
        } 
    } 
    

    就是这样。保持简单和干净。每件事都有自己明确的责任。

+0

JavaMail API充满了静态方法调用,这会使您的代码难以测试。如果您可以选择使用Spring,请查看MailSender API(http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mail.html)。 – 2010-10-25 02:47:30

+0

看起来您的发送(从,到,主题,消息)与http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html(sendMail方法)有点不同。 – user3014926 2014-01-11 05:23:26

+0

你的梅勒的send()方法是什么样的? – user3014926 2014-01-11 05:24:16

1

JSP页面:

<form action="mail.do" method="POST"> 
<table> 
    <tr> 
    <td>To Email-id :<input type="text" name="email" /></td> <!--enter the email whom to send mail --> 
    <td><input type="submit" value="send"></input></td> 
    </tr> 
</table> 
</form> 

这里的servlet代码:

String uri=req.getRequestURI(); 

if(uri.equals("/mail.do")) 
     { 
      SendEmail sa=new SendEmail(); 
         String to_mail=request.getParameter("email"); 
         String body="<html><body><table width=100%><tr><td>Hi this is Test mail</td></tr></table></body></html>"; 
      sa.SendingEmail(to_email,body); 

     } 

而且SendEmail类:

package Email; 

import java.util.Properties; 

import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 

public class SendEmail { 

    public void SendingEmail(String Email,String Body) throws AddressException, MessagingException 
    { 

      String host ="smtp.gmail.com"; 
      String from ="yourMailId"; //Your mail id 
      String pass ="yourPassword"; // Your Password 
      Properties props = System.getProperties(); 
      props.put("mail.smtp.starttls.enable", "true"); // added this line 
      props.put("mail.smtp.host", host); 
      props.put("mail.smtp.user", from); 
      props.put("mail.smtp.password", pass); 
      props.put("mail.smtp.port", "25"); 
      props.put("mail.smtp.auth", "true"); 
      String[] to = {Email}; // To Email address 
      Session session = Session.getDefaultInstance(props, null); 
      MimeMessage message = new MimeMessage(session); 
      message.setFrom(new InternetAddress(from)); 
      InternetAddress[] toAddress = new InternetAddress[to.length];   
      // To get the array of addresses 
       for(int i=0; i < to.length; i++) 
       { // changed from a while loop 
        toAddress[i] = new InternetAddress(to[i]); 
       } 
      System.out.println(Message.RecipientType.TO); 
      for(int j=0; j < toAddress.length; j++) 
      { // changed from a while loop 
      message.addRecipient(Message.RecipientType.TO, toAddress[j]); 
      } 
      message.setSubject("Email from SciArchives"); 

      message.setContent(Body,"text/html"); 
      Transport transport = session.getTransport("smtp"); 
      transport.connect(host, from, pass); 
      transport.sendMessage(message, message.getAllRecipients()); 
       transport.close(); 
     } 
    } 
-1

这基本设置工作得很好:

进口的mail.jar的activation.jarWEB_INF/lib目录内的项目文件夹。

的JavaMail(从官方网站最新版本)得到的mail.jar

得到的activation.jarhttp://www.oracle.com/technetwork/java/javase/jaf-136260.html

1.第一JSP:emailForm.jsp

这是用于传递发送者,接收者细则,主题和消息内容到emailUtility一个形式

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1"%> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    <title>Send email</title> 
    </head> 
    <body> 
     <form action="emailUtility.jsp" method="post"> 
      <table border="0" width="35%" align="center"> 
       <caption><h2>Send email using SMTP</h2></caption> 
       <tr> 
        <td width="50%">Sender address </td> 
        <td><input type="text" name="from" size="50"/></td> 
       </tr> 
       <tr> 
        <td width="50%">Recipient address </td> 
        <td><input type="text" name="to" size="50"/></td> 
       </tr> 
       <tr> 
        <td>Subject </td> 
        <td><input type="text" name="subject" size="50"/></td> 
       </tr> 
       <tr> 
        <td>Message Text </td> 
        <td><input type="text" name="messageText"></td> 
       </tr> 
       <tr> 
        <td colspan="2" align="center"><input type="submit" value="Send"/></td> 
       </tr> 
      </table> 

     </form> 
    </body> 
    </html> 

2.第二个JSP:emailUtility.jsp

这是在前面的jsp(emailForm.jsp)中提到的表单操作。

<html> 
<head> 
<title>email utility</title> 
</head> 
<body> 
<%@ page import="java.util.*" %> 
<%@ page import="javax.mail.*" %> 
<%@ page import="javax.mail.internet.*" %> 
<%@ page import="javax.activation.*" %> 
<% 
String host = "smtp.gmail.com"; 
String to = request.getParameter("to");  

String from = request.getParameter("from"); 

String subject = request.getParameter("subject"); 

String messageText = request.getParameter("messageText"); 

boolean sessionDebug = false; 
// Create some properties and get the default Session. 
Properties props = System.getProperties(); 
props.put("mail.host", host); 
props.put("mail.transport.protocol", "smtp"); 
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 mailSession = Session.getDefaultInstance(props, 
    new javax.mail.Authenticator(){ 
     protected PasswordAuthentication getPasswordAuthentication() { 
      return new PasswordAuthentication(
      "[email protected]", "password_here");// Specify the Username and the PassWord 
     } 
    }); 
// Set debug on the Session 
// Passing false will not echo debug info, and passing True will. 

mailSession.setDebug(sessionDebug); 

// Instantiate a new MimeMessage and fill it with the 
// required information. 

Message msg = new MimeMessage(mailSession); 
msg.setFrom(new InternetAddress(from)); 
InternetAddress[] address = {new InternetAddress(to)}; 
msg.setRecipients(Message.RecipientType.TO, address); 
msg.setSubject(subject); 
msg.setSentDate(new Date()); 
msg.setText(messageText); 

// Hand the message to the default transport service 
// for delivery. 
Transport.send(msg); 
out.println("Mail was sent to " + to); 
out.println(" from " + from); 
out.println(" using host " + host + "."); 
%> 
</table> 
</body> 
</html> 

3.进入以下网址

http://localhost:8080/projectname/emailForm.jsp

4.重新启动,如果它插上U服务器错误服务器。