Skip to main content

HOW TO SEND AND EMAIL USING JAVA APPLICATION

Simple example to send an email (without attachment ) using java application

Syntax :

Example :

  1. import javax.mail.Session;
  2. import javax.mail.Message;
  3. import javax.mail.Transport;
  4. import javax.mail.MessagingException;
  5. import javax.mail.internet.MimeMessage;
  6. import javax.mail.internet.InternetAddress;
  7. import java.util.Properties;
  8.  
  9. public class Main {
  10.   public static void main(String[] args) {
  11.     String from = "user@some-domain.com";
  12.     String to = "user@some-domain.com";
  13.     String subject = "Hi There...";
  14.     String text = "How are you?";
  15.  
  16.     Properties properties = new Properties();
  17.     properties.put("mail.smtp.host", "smtp.some-domain.com");
  18.     properties.put("mail.smtp.port", "25");
  19.     Session session = Session.getDefaultInstance(properties, null);
  20.  
  21.     Message message = new MimeMessage(session);
  22.     message.setFrom(new InternetAddress(from));
  23.     message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
  24.     message.setSubject(subject);
  25.     message.setText(text);
  26.  
  27.     Transport.send(message);
  28.   }
  29. }

Description :

Step 1 - 7 : Importing all files.
Step 9 : Start of main class
Step 16-19 :Properties class represents persistant set of properties.They can be saved to stream or loaded                       from stream.
Step 21-25 :Message implements part interface. Message  contains set of attributes and "contents". Message                    defines new attributes in addition to those defined in part interface.