Servlet - Invio di e-mail

Inviare un'e-mail utilizzando il tuo a Servlet è abbastanza semplice, ma per iniziare dovresti averlo JavaMail API e Java Activation Framework (JAF) installato sulla tua macchina.

Scarica e decomprimi questi file, nelle directory di primo livello appena create troverai una serie di file jar per entrambe le applicazioni. Devi aggiungeremail.jar e activation.jar file nel tuo CLASSPATH.

Invia una semplice email

Ecco un esempio per inviare una semplice email dalla tua macchina. Qui si presume che il tuo filelocalhostè connesso a Internet e in grado di inviare un'e-mail. Allo stesso tempo assicurati che tutti i file jar dal pacchetto Java Email API e dal pacchetto JAF siano disponibili in CLASSPATH.

// File Name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";
 
      // Sender's email ID needs to be mentioned
      String from = "[email protected]";
 
      // Assuming you are sending email from localhost
      String host = "localhost";
 
      // Get system properties
      Properties properties = System.getProperties();
 
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
 
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try {
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
         
         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));
         
         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
         
         // Set Subject: header field
         message.setSubject("This is the Subject Line!");
         
         // Now set the actual message
         message.setText("This is actual message");
         
         // Send message
         Transport.send(message);
         String title = "Send Email";
         String res = "Sent message successfully....";
         String docType =
            "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         
         out.println(docType +
            "<html>\n" +
               "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor = \"#f0f0f0\">\n" +
                  "<h1 align = \"center\">" + title + "</h1>\n" +
                  "<p align = \"center\">" + res + "</p>\n" +
               "</body>
            </html>"
         );
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Ora compiliamo il servlet sopra e creiamo le seguenti voci in web.xml

....
 <servlet>
   <servlet-name>SendEmail</servlet-name>
   <servlet-class>SendEmail</servlet-class>
</servlet>
 
<servlet-mapping>
   <servlet-name>SendEmail</servlet-name>
   <url-pattern>/SendEmail</url-pattern>
</servlet-mapping>
....

Ora chiama questo servlet utilizzando l'URL http: // localhost: 8080 / SendEmail che invierebbe un'e-mail al dato ID e -mail [email protected] e visualizzerebbe la seguente risposta:

Send Email

Sent message successfully....

Se desideri inviare un'e-mail a più destinatari, verranno utilizzati i seguenti metodi per specificare più ID e-mail:

void addRecipients(Message.RecipientType type, Address[] addresses)
throws MessagingException

Ecco la descrizione dei parametri:

  • type- Questo sarebbe impostato su TO, CC o BCC. Qui CC rappresenta Carbon Copy e BCC rappresenta Black Carbon Copy. Message.RecipientType.TO di esempio

  • addresses- Questa è la matrice dell'ID e-mail. Dovresti usare il metodo InternetAddress () mentre specifichi gli ID email.

Invia un'e-mail HTML

Ecco un esempio per inviare un'e-mail HTML dalla tua macchina. Qui si presume che il tuo filelocalhostè connesso a Internet e in grado di inviare un'e-mail. Allo stesso tempo, assicurati che tutti i file jar dal pacchetto Java Email API e dal pacchetto JAF siano disponibili in CLASSPATH.

Questo esempio è molto simile al precedente, tranne che qui stiamo usando il metodo setContent () per impostare il contenuto il cui secondo argomento è "text / html" per specificare che il contenuto HTML è incluso nel messaggio.

Usando questo esempio, puoi inviare un contenuto HTML grande quanto ti piace.

// File Name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail extends HttpServlet {
    
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";
 
      // Sender's email ID needs to be mentioned
      String from = "[email protected]";
 
      // Assuming you are sending email from localhost
      String host = "localhost";
 
      // Get system properties
      Properties properties = System.getProperties();
 
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
 
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try {
         
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
         
         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));
         
         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Send the actual HTML message, as big as you like
         message.setContent("<h1>This is actual message</h1>", "text/html" );
         
         // Send message
         Transport.send(message);
         String title = "Send Email";
         String res = "Sent message successfully....";
         String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         
         out.println(docType +
            "<html>\n" +
               "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor = \"#f0f0f0\">\n" +
                  "<h1 align = \"center\">" + title + "</h1>\n" +
                  "<p align = \"center\">" + res + "</p>\n" +
               "</body>
            </html>"
         );
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compila ed esegui il servlet sopra per inviare un messaggio HTML su un determinato ID email.

Invia allegato in e-mail

Ecco un esempio per inviare un'e-mail con allegato dal tuo computer. Qui si presume che il tuo filelocalhost è connesso a Internet e in grado di inviare un'e-mail.

// File Name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";
 
      // Sender's email ID needs to be mentioned
      String from = "[email protected]";
 
      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();
 
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
 
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      
	  // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try {
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
 
         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));
 
         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
 
         // Set Subject: header field
         message.setSubject("This is the Subject Line!");
 
         // Create the message part 
         BodyPart messageBodyPart = new MimeBodyPart();
 
         // Fill the message
         messageBodyPart.setText("This is message body");
         
         // Create a multipar message
         Multipart multipart = new MimeMultipart();
 
         // Set text message part
         multipart.addBodyPart(messageBodyPart);
 
         // Part two is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "file.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);
 
         // Send the complete message parts
         message.setContent(multipart );
 
         // Send message
         Transport.send(message);
         String title = "Send Email";
         String res = "Sent message successfully....";
         String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         
         out.println(docType +
            "<html>\n" +
               "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor = \"#f0f0f0\">\n" +
                  "<h1 align = \"center\">" + title + "</h1>\n" +
                  "<p align = \"center\">" + res + "</p>\n" +
               "</body>
            </html>"
         );
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compila ed esegui il servlet sopra per inviare un file come allegato insieme a un messaggio su un determinato ID email.

Parte autenticazione utente

Se è necessario fornire l'ID utente e la password al server di posta elettronica a scopo di autenticazione, è possibile impostare queste proprietà come segue:

props.setProperty("mail.user", "myuser");
 props.setProperty("mail.password", "mypwd");

Il resto del meccanismo di invio delle e-mail rimarrebbe come spiegato sopra.