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 = "";
  String to = "contact@localhost";
  String subject = "Demo Subject";
  String body = "Demo Body";

  Properties props = new Properties();

  // mail server host name and port
  props.put("", "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.setRecipient(RecipientType.TO, toAddress);

  // Send Message




No comments:

Post a Comment