Sending email with Html content

Example of sending html content with email in Java provides examples of sending, receiving, forwarding and deleting emails, Learn how to send HTML email in java

Sending email with Html content

Sending email with Html content

As we send the email, we can send the html content also.

For better understanding of this example, learn the steps of sending email using JavaMail API first.

For receiving or sending the email using JavaMail API, you need to load the two jar files:

  • mail.jar
  • activation.jar

Example of sending email with html content using JavaMail API

 

  1. import java.util.*;  
  2. import javax.mail.*;  
  3. import javax.mail.internet.*;  
  4. import javax.activation.*;  
  5.   
  6. class SendHtmlEmail  
  7. {  
  8.    public static void main(String [] args)  
  9.    {  
  10.   
  11.       String host="mail.samtpoint.com";//change accordingly  
  12.       String to="sam@gmail.com";//change accordingly  
  13.       final String user="sam@amtpoint.com";//change accordingly  
  14.       final String password="xxxxx";//change accordingly  
  15.   
  16.       Properties properties = System.getProperties();  
  17.       properties.setProperty("mail.smtp.host", );  
  18.       properties.put("mail.smtp.auth""true");  
  19.   
  20.       Session session = Session.getDefaultInstance(properties,  
  21.     new javax.mail.Authenticator() {  
  22.      protected PasswordAuthentication getPasswordAuthentication() {  
  23.       return new PasswordAuthentication(user,password);  
  24.      }  
  25.       });  
  26.         
  27.       try{  
  28.          MimeMessage message = new MimeMessage(session);  
  29.          message.setFrom(new InternetAddress(user));  
  30.          message.addRecipient(Message.RecipientType.TO,  
  31.                                   new InternetAddress(to));  
  32.   
  33.         message.setSubject("HTML Message");  
  34.         message.setContent("<h1>sending html mail check</h1>","text/html" );  
  35.     
  36.        Transport.send(message);  
  37.          System.out.println("message sent....");  
  38.       }catch (MessagingException ex) {ex.printStackTrace();}  
  39.    }  
Load the jar file c:\> set classpath=mail.jar;activation.jar;.;
compile the source file c:\> javac SendHtmlEmail.java
run by c:\> java SendHtmlEmail