2010-09-21 72 views
7

¿Cómo enviar un correo electrónico desde JSP/servlet? ¿Es necesario descargar algunos tarros o puede enviar un correo electrónico desde JSP/servlets sin tarros?¿Cómo enviar un correo electrónico desde jsp/servlet?

  • ¿Cómo sería el código de mi Java?

  • ¿Cómo se vería mi código HTML (si corresponde)?

  • ¿Son necesarias múltiples clases, o puede usar solo una clase?

+7

Busque en Google esas preguntas triviales antes de publicar en SO. Los siguientes enlaces están entre los primeros diez resultados. –

+4

Google está sujeto a resultados populares. La gente usa StackOverflow para obtener la opinión de la gente real a diferencia de los algoritmos de Mountain View.Ese es el objetivo de StackOverflow en mi humilde opinión. – MonoThreaded

+0

obtener meta, ese es el punto del sistema de puntos. un buen q/a obtiene más puntos, aparece más en las búsquedas, etc. ... pero, sí, mejores resultados (con suerte). idea similar al rango de página, aunque. – Thufir

Respuesta

2

estoy usando el paquete Javamail y funciona muy bien. Las muestras que se muestran arriba son buenas, pero como puedo ver, no definieron parámetros en un archivo externo (por ejemplo, web.xml) que se recomienda ...

Imagine que desea cambiar su dirección de correo electrónico o host SMTP. Es mucho más fácil editar el archivo web.xml que 10 servlets donde utilizó la función de correo. Por ejemplo añadir siguientes líneas en web.xml

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

A continuación, puede acceder a los parámetros del servlet con

// 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

La lógica anuncio publicitario debe ir en su propia clase independiente que puede volver a utilizar en todas partes. El archivo JSP solo debe contener lógica de presentación y marcado. La clase Servlet solo debe procesar la solicitud de la forma adecuada y llamar a la clase de correo. Estos son los pasos que debes seguir:

  1. En primer lugar decidir qué SMTP server desea utilizar de modo que usted será capaz de enviar mensajes de correo electrónico. ¿El de tu ISP? ¿El de Gmail? Yahoo? Proveedor de alojamiento web? ¿Uno autosuficiente? De todos modos, calcule el nombre de host, el puerto, el nombre de usuario y la contraseña de este servidor SMTP. Necesitarás esta información.


  2. crear una clase Java con sabor de vainilla que utiliza JavaMail API para enviar un mensaje de correo. La API de JavaMail viene con una excelente tutorial y FAQ. Nombra la clase Mailer y dale un método send() (o lo que quieras). Prueba de que el uso de alguna clase probador con un método main() así:

    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); 
        } 
    } 
    

    Puede que sea lo más simple o avanzado como desee. No importa, siempre y cuando tenga una clase con la que pueda enviar un correo como ese.


  3. Ahora la parte JSP, no es del todo claro por qué usted ha mencionado JSP, pero desde un JSP es supposed para representar solamente HTML, apuesto que le gustaría tener algo así como un formulario de contacto en un JSP .Aquí hay un ejemplo de patada de salida:

    <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> 
    

    Sí, simple, simplemente marque/estilo de la manera que desee.


  4. Ahora, crear una clase Servlet que escucha en un url-pattern de /contact (la misma que la forma se somete a) y aplicar el doPost() método (el mismo método que el formulario está utilizando) como sigue:

    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); 
         } 
        } 
    } 
    

    Eso es todo. Mantenlo simple y limpio. Cada cosa tiene sus propias responsabilidades claras.

    página
+0

La API de JavaMail está llena de llamadas a métodos estáticos que dificultarán la prueba de su código. Si tiene la opción de usar Spring, consulte la API de MailSender (http://static.springsource.org/spring/docs/3.0.x/spring- framework-reference/html/mail.html). –

+0

Parece que su mensaje de envío (de, a, sujeto) es un poco diferente de http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html (método sendMail). – user3014926

+0

¿Cómo era el método de enviar() de su Mailer? – user3014926

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> 

Aquí está el código 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); 

     } 

Y la clase 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

Esta configuración básica funcionó bien:

importación mail.jar y activation.jar en WEB_INF/lib carpeta dentro del proyecto.

obtener mail.jar de JavaMail (última versión del sitio oficial).

obtener activation.jar de http://www.oracle.com/technetwork/java/javase/jaf-136260.html

1. En primer lugar jsp: emailForm.jsp

Ésta es una forma utilizada para pasar el emisor, receptor detalles, asunto y mensaje contenido al 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. En segundo lugar jsp: emailUtility.jsp

Esta es la acción de formulario mencionada en el jsp anterior (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. Ir a la siguiente URL

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

4. Reinicie el servidor si se da u error del servidor.

Cuestiones relacionadas