InfoCenter Home >
4: Developing applications >
4.6: Java Technologies >
4.6.1: Using JavaMail >
4.6.1.1: Writing JavaMail applications

4.6.1.1: Writing JavaMail applications

According to the J2EE specifications, each javax.mail.Session instance must be treated as a resource factory. Therefore, to use JavaMail, do the following:

  1. Declare mail resource references in your application component's deployment descriptors, as described in this example:
    <resource-ref>
    <description>description</description>
    <res-ref-name>mail/MailSession</res-ref-name>
    <res-type>javax.mail.Session</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    
  2. Configure, during deployment, each referenced mail resource. See article, 4.6.1.2: Configuring JavaMail, for a description of the parameters required to configure a mail resource.
  3. Locate in your application component, during runtime, each specific JavaMail session using JNDI lookup. An example of the code follows:
    Session session = (Session)ctx.lookup("java:comp/env/mail/MailSession");

    Your application component can now use session to create messages and get store access.

Coding example for sending and saving a message

The following code segment shows how an application component sends a message and saves it to the mail account's Sent folder:

    javax.naming.InitialContext ctx = new javax.naming.InitialContext();
    
    mail_session = (javax.mail.Session) ctx.lookup("java:comp/env/mail/MailSession");

    MimeMessage msg = new MimeMessage(mail_session);
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("bob@coldmail.net"));

    msg.setFrom(new InternetAddress("alice@mail.eedge.com"));
    msg.setSubject("Important message from eEdge.com");
    msg.setText(msg_text);
    Transport.send(msg);

    Store store = mail_session.getStore();
    store.connect();
    Folder f = store.getFolder("Sent");
    if (!f.exists()) f.create(Folder.HOLDS_MESSAGES);
    f.appendMessages(new Message[] {msg});

See the related information links for the JavaMail APIs.

Go to previous article: Using JavaMail Go to next article: Configuring JavaMail

 

 
Go to previous article: Using JavaMail Go to next article: Configuring JavaMail