Thursday, July 15, 2010

Java Code to Send E-Mail


  • You can send or fetch e-mail through your Java application or servlet using the JavaMail API.
  • You use the JavaMail API where as JavaMail implementation providers implement the JavaMail API to give you a JavaMail client (Java JAR file). Sun gives you mail.jar which has Sun's SMTP, POP3 and IMAP client implementations along with the JavaMail API. This is sufficient to send and receive e-mail but not to read or post to newgroups which use NNTP.

  • To compile and run, you must have mail.jar (from the JavaMail download) and activation.jar (from the JavaBeans Activation Framework download) in Java classpath.
  • You need to replace email addresses and mail server with your values where noted. Username and password is generally not needed to send e-mail although your ISP may still require it to prevent spam from going through its systems.
  • This sample code has debugging turned on ("mail.debug") to see what is going on behind the scenes in JavaMail code.
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;

    // Send a simple, single part, text/plain e-mail
    public class TestEmail {

    public static void main(String[] args) {

    // SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
    String to = "subh@subh.com";
    String from = "subh@subh.com";
    // SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
    String host = "smtp.yourisp.net";

    // Create properties, get Session
    Properties props = new Properties();

    // If using static Transport.send(),
    // need to specify which host to send it to
    props.put("mail.smtp.host", host);
    // To see what is going on behind the scene
    props.put("mail.debug", "true");
    Session session = Session.getInstance(props);

    try {
    // Instantiatee a message
    Message msg = new MimeMessage(session);

    //Set message attributes
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("Test E-Mail through Java");
    msg.setSentDate(new Date());

    // Set message content
    msg.setText("This is a test of sending a " +
    "plain text e-mail through Java.\n" +
    "Here is line 2.");


    //Send the message
    Transport.send(msg);
    }
    catch (MessagingException mex) {
    // Prints all nested (chained) exceptions as well
    mex.printStackTrace();
    }
    }
    }//End of class

No comments:

Post a Comment