Sending an email using JavaMail

This example assumes you have JavaMail1.2 installed. It can be downloaded from http://java.sun.com/products/javamail/. Add both mail.jar and activation.jar to your classpath.

Set the property mail.smtp.host with your SMTP host, create a session, tie it to your message and send it with the Transport class. It’s that simple!

SendMessage.java:

import javax.mail.internet.*;
import javax.mail.*;
import java.util.*;
 
public class SendMessage
{
   public static void main(String []args) {
      try {
         String host = "fill in your SMTP host here";
         String from = "FROM email address";
         String to   = "TO email address";
 
         Properties properties = new Properties();
         properties.put("mail.smtp.host", host);
 
         Session session = Session.getDefaultInstance(properties);
 
         MimeMessage message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
 
         message.setSubject("Hi!");
         message.setText("I send you this file in order to have your advice");
 
         Transport.send(message);
      }
      catch(MessagingException e) {
         e.printStackTrace();
      }
   }
}