Sunday 19 February 2012

Sending mail using Java

Send Mail Using Java Mail API:

Following example demonstrates simply methodology to send mail using java mail api. Here the mail server is running on localhost and listening on port 19025.  Java Mail API uses SMTP protocol to send mails.

Generally mail servers are configured to listed on standard SMTP port 25. Here apache james mail server is listing on Port 19025.

 
package demo;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

/**
 * Send mail using SMTP Protocol
 * 
 * @author luckyacademy
 */
public class SendMailDemo {

 public static void main(String[] args) throws Exception {
  String from = "abc@gmail.com";
  String to = "contact@localhost";
  String subject = "Demo Subject";
  String body = "Demo Body";

  Properties props = new Properties();

  // mail server host name and port
  props.put("mail.smtp.host", "localhost");
  props.put("mail.smtp.port", "19025");

  // Get Session
  Session mailSession = Session.getDefaultInstance(props);

  // Create a message object
  Message simpleMessage = new MimeMessage(mailSession);

  InternetAddress fromAddress = new InternetAddress(from);
  InternetAddress toAddress = new InternetAddress(to);

  simpleMessage.setFrom(fromAddress);
  simpleMessage.setRecipient(RecipientType.TO, toAddress);
  simpleMessage.setSubject(subject);
  simpleMessage.setText(body);

  // Send Message
  Transport.send(simpleMessage);

 }

}

 

No comments:

Post a Comment