Before you begin
Using JavaMail API, a code segment can be embedded in any Java 2 Enterprise Edition (J2EE) application component, such as an EJB or a servlet, allowing the application to send a message and save a copy of the mail to the Sent folder.The following is a code sample that you would embed in a J2EE application:
javax.naming.InitialContext ctx = new javax.naming.InitialContext(); javax.mail.Session mail_session = (javax.mail.Session) ctx.lookup("java:comp/env/mail/MailSession3"); 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});
Why and when to perform this task
J2EE applications can use JavaMail APIs by looking up references to logically named mail connection factories through the java:comp/env/mail subcontext declared in the application deployment descriptor and mapped to installation specific mail session resources. As in the case of other J2EE resources, this can be done in order to eliminate the need for the application to hard code references to external resources.Steps for this task
In the sample code above, the line javax.mail.Session mail_session = (javax.mail.Session) ctx.lookup("java:comp/env/mail/MailSession3"); is an example of not hard coding a mail session and using a resource name located through JNDI. You can consider the lookup name mail/MailSession3, as a soft link to the real resource.
When you create this reference, be sure that the name of the reference matches the name used in the code. For example, the code above uses java:comp/env/mail/MailSession3 in its lookup, therefore the name of this reference must be mail/Session3 and the type of the resource must be javax.mail.Session. After being defined, the deployment descriptor contains the following entry for the mail resource reference:
<resource-reference> <description>description</description> <res-ref-name>mail/MailSession3</res-ref-name> <res-type>javax.mail.Session</res-type> <res-auth>Container</res-auth>
To update mail providers and sessions:
What to do next
If your application has a client, you can update mail providers and mail sessions using the Application Client Resource Configuration Tool (ACRCT).