JavaMail

From Oxxus Wiki

Jump to: navigation, search

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.

The JavaMail API is a set of abstract APIs that model a mail system. The API provides a platform independent and protocol independent framework to build Java technology based email client applications. The JavaMail API provides facilities for reading and sending email. Service providers implement particular protocols. Several service providers are included with the JavaMail API package; others are available separately. The JavaMail API is implemented as a Java optional package that can be used on JDK 1.4 and later on any operating system. The JavaMail API is also a required part of the Java Platform, Enterprise Edition (Java EE).

Contents

Required libraries

To use JavaMail you will need two libraries JavaMail and Java Activation Framework.

They are available by default and come with our installation package for Tomcat.

Setting up resource

Edit your context.xml file and declare a resource.

<Resource auth="Container" mail.smtp.host="localhost" name="mail/MyMailResource" type="javax.mail.Session"/>

Edit your web.xml and declare that that your application will be using the resource.

<resource-ref>
  <description>MyMailResource description </description>
  <res-ref-name>mail/MyMailResource</res-ref-name>
  <res-type>javax.mail.Session</res-type>
  <res-auth>Container</res-auth>
  <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

Now you're ready to use JavaMail with your application.

JavaMail example

Session session = null;
try {
  Context initCtx = new InitialContext();
  Context envCtx = (Context) initCtx.lookup("java:comp/env");
  session = (Session) envCtx.lookup("mail/MyMailResource");
} catch (Exception ex) {
  System.out.println(ex.getMessage());
}

Message message = new MimeMessage(session);
try {
  message.setFrom(new InternetAddress(sender);
  InternetAddress to[] = new InternetAddress[1];
  to[0] = new InternetAddress(receiver);
  message.setRecipients(Message.RecipientType.TO, to);
  message.setSubject(subject);
  message.setContent(body, "text/html;charset=UTF-8");
  Transport.send(message);
} catch (AddressException ex) {
  System.out.println(ex.getMessage());
} catch (MessagingException ex) {
  System.out.println(ex.getMessage());
}

External links

Contact About Us Support Network Servers Java Hosting Oxxus.net Order Now! Dedicated Servers VPS Hosting Tomcat Hosting Java Hosting Money Back Guarantee Privacy Policy Oxxus.net Terms of 
Service Contact About Us Servers Networks Support Domain Names SSL Certificates Java Wiki Tutorials E-learning 
Platforms