Latest web development tutorials

Servlet email

Send an e-mail using the Servlet is very simple, but first you must installJavaMail API and the Java Activation Framework)on your computerJAF).

  • You can download the latest version of Java the JavaMail , open the right side of the page there is a Downloads link, click on it to download.
  • You can download the latest version of Java (Version 1.1.1) JAF .

You can also use the site to provide download link:

Download and unzip the files in the newly created top-level directory, you'll find some jar file two applications. You need to addmail.jar and activation.jarfiles to your CLASSPATH.

Send a simple e-mail

The following examples send a simple e-mail from your computer. This assumes yourlocal host is connected to the Internet and e-mail support.While ensuring that Java Email API packages and JAF package all jar files in the CLASSPATH are available.

// Filename 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
  {
      // The recipient's e-mail ID
      String to = "[email protected]";
 
      // Sender's e-mail ID
      String from = "[email protected]";
 
      // Let's say you send e-mail String host = "localhost" from the local host;
 
      // Get system properties Properties properties = System.getProperties ();
 
      // Set up a mail server properties.setProperty ( "mail.smtp.host", host);
 
      // Get the default Session object Session session = Session.getDefaultInstance (properties);
      
      // Set the response content type response.setContentType ( "text / html; charset = UTF-8");
      PrintWriter out = response.getWriter ();

      try {
         // Create a default MimeMessage objects MimeMessage message = new MimeMessage (session);
         // Set the 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 the Subject: header field
         message.setSubject ( "This is the Subject Line!");
         // Now set the actual message message.setText ( "This is actual message");
         // Send the message Transport.send (message);
         String title = "email";
         String res = "successfully sent messages ...";
         String docType = "\ n <DOCTYPE html!>";
         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 ();
      }
   }
} 

Now let's compile the above Servlet, and create the following entry in the web.xml file:

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

Now by visiting the URL http: // localhost: 8080 / SendEmail to call this Servlet. This will send an email to the given emailID[email protected], and will appear as shown in the following response:

send email

Successfully sent a message ...

If you want to send an e-mail to multiple recipients, use the following methods to specify multiple e-mail ID:

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

The following is a description of the parameters:

  • type: This will be set as TO, CC, or BCC.Here, CC on behalf of CC, BCC BCC representatives. For exampleMessage.RecipientType.TO.
  • addresses: This is an array of e-mail ID.When specifying e-mail ID, you need to use InternetAddress () method.

Send an HTML e-mail

The following example will send an HTML-formatted e-mail on your computer. This assumes yourlocal host is connected to the Internet and e-mail support.While ensuring that Java Email API packages and JAF package all jar files in the CLASSPATH are available.

This example is very similar to the previous examples, but here we use setContent () method to set the second parameter is "text / html" content, this parameter is used to specify the HTML content contained in the message.

Using this instance, you can send the content is not limited to the size of the HTML content.

// Filename 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
  {
      // The recipient's e-mail ID
      String to = "[email protected]";
 
      // Sender's e-mail ID
      String from = "[email protected]";
 
      // Let's say you send e-mail String host = "localhost" from the local host;
 
      // Get system properties Properties properties = System.getProperties ();
 
      // Set up a mail server properties.setProperty ( "mail.smtp.host", host);
 
      // Get the default Session object Session session = Session.getDefaultInstance (properties);
      
	  // Set the response content type response.setContentType ( "text / html; charset = UTF-8");
      PrintWriter out = response.getWriter ();

      try {
         // Create a default MimeMessage objects MimeMessage message = new MimeMessage (session);
         // Set the 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 the Subject: header field
         message.setSubject ( "This is the Subject Line!");

         // Set the actual HTML message content size limited message.setContent ( "<h1> This is actual message </ h1>",
                            "Text / html");
         // Send the message Transport.send (message);
         String title = "email";
         String res = "successfully sent messages ...";
         String docType = "\ n <DOCTYPE html!>";
         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 ();
      }
   }
} 

Compile and run the above Servlet, send HTML messages on a given e-mail ID.

Send attachments in e-mail

The following examples send an e-mail with an attachment on your computer will be. This assumes yourlocal host is connected to the Internet and e-mail support.While ensuring that Java Email API packages and JAF package all jar files in the CLASSPATH are available.

// Filename 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
  {
      // The recipient's e-mail ID
      String to = "[email protected]";
 
      // Sender's e-mail ID
      String from = "[email protected]";
 
      // Let's say you send e-mail String host = "localhost" from the local host;
 
      // Get system properties Properties properties = System.getProperties ();
 
      // Set up a mail server properties.setProperty ( "mail.smtp.host", host);
 
      // Get the default Session object Session session = Session.getDefaultInstance (properties);
      
	  // Set the response content type response.setContentType ( "text / html; charset = UTF-8");
      PrintWriter out = response.getWriter ();

       try {
         // Create a default MimeMessage objects MimeMessage message = new MimeMessage (session);
 
         // Set the 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 the Subject: header field
         message.setSubject ( "This is the Subject Line!");
 
         // Create a message part BodyPart messageBodyPart = new MimeBodyPart ();
 
         // Fill in a message messageBodyPart.setText ( "This is message body");
         
         // Create a multi-part message Multipart multipart = new MimeMultipart ();
 
         // Set text message parts multipart.addBodyPart (messageBodyPart);
 
         // The second part is an accessory messageBodyPart = new MimeBodyPart ();
         String filename = "file.txt";
         DataSource source = new FileDataSource (filename);
         messageBodyPart.setDataHandler (new DataHandler (source));
         messageBodyPart.setFileName (filename);
         multipart.addBodyPart (messageBodyPart);
 
         // Send a complete message part message.setContent (multipart);
 
         // Send the message Transport.send (message);
         String title = "email";
         String res = "successfully send e-mail ...";
         String docType = "\ n <DOCTYPE html!>";
         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 ();
      }
   }
} 

Compile and run the above Servlet, send messages with file attachments on a given e-mail ID.

User authentication section

If you need to provide the e-mail server user ID and password authentication, you can set the following properties:

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

The rest of the e-mail delivery mechanism is consistent with the above explain.