May 13, 2014

Sending mail Using JavaMail

To sending email using Mime Message, Message, Session, Transport, XXXException import from javax.mail package. Those classes contains below jars:

j2ee.jar or (mail.jar and activation.jar)

If using j2ee.jar , you may get error : NoClassDefFoundError.

Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Address

So, we need import mail.jar and activation.jar files, then NoClassDefFoundError error resolve automatically.

Send an email message, an application prepares a MimeMessage object, then sends it with the static method send() on the Transport class in javax.mail package. The message is created using a JavaMail Session object. The Session and the Transport work with the Application Engine Mail service without any additional configuration to this method.


import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

//..

private static void sendMail(){

       
Properties props = new Properties();
        String smtpHost = "smtp.corp.anthem.com";
                    props.put("mail.imaps.partialfetch", "false");
                    props.put("mail.smtp.host", smtpHost);
        Session session = Session.getInstance(props, null); or Session.getDefaultInstance(props, null);
       
String msgBody = "...";

       
try {
           
Message msg = new MimeMessage(session);
            msg
.setFrom(new InternetAddress("fromTeam@example.com", "XXX@XMail.com Admin"));
            msg
.addRecipient(Message.RecipientType.TO,
                             
new InternetAddress("enduser@example.com", "Mr. EndUser"));
            msg
.setSubject("Your XXX  account has been activated");
            msg
.setText(msgBody);
           
Transport.send(msg);

       
} catch (AddressException e) {
           
// ...
       
} catch (MessagingException e) {
           
// ...
       
}
}


if you want more information mail parameters, please visit below web page:
JavaMail


No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts