Sending Email thru JAVA Mail API
My Application Leave Application System requires to send a mail. So i have decided to use JAVA Mail Api.
Requirement is once the employee apply a leave thru Leave Application system which has to notify about this leave to the reporting authority thru mail.
Here is the code for sending mail.
package org.val.system.la.service.external;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/* This application checks authentication of the sender */
public class SendApp extends Authenticator {
public static void send( String smtpHost, int smtpPort, String from, String to, String subject, String content ) throws AddressException, MessagingException {
java.util.Properties props = System.getProperties();
props.put( "mail.smtp.host", smtpHost );
props.put( "mail.smtp.port", "" + smtpPort );
props.put( "mail.smtp.auth", "true" );
Session session = Session.getDefaultInstance( props, new SendApp() );
Message msg = new MimeMessage( session );
msg.setFrom( new InternetAddress( from ) );
msg.setRecipient( Message.RecipientType.TO, new InternetAddress( to ) );
msg.setRecipient( Message.RecipientType.CC, new InternetAddress( from ) );
msg.setSubject( subject );
msg.setContent( content, "text/html" );
Transport.send( msg );
}
public static void main( String[] args ) throws Exception {
send( "YOURSMTPHOST", 10, "FromAddress", "ToAddress", "Subject", "MessageContent" );
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( "username", "password" );
}
}
The above code is self explanatory. Now you can send email to dear one :-)
No comments:
Post a Comment