Sometimes we need to send mail from within our application. In java there is an API which supports sending and receiving emails.
In order to send mail from a java application we need to add two jars in our application:
1.Mail.jar
2.Activation.jar
The following import statements should be include in java code.
import javax.mail.*; import java.mail.internet.*; import java.util.Porpterties;
Setup Mail Server:
Before sending mail we need to setup the mail server as below:
Properties prop = System.getProperties(); prop.put(“mail.smtp.host”, mail server name/ip);
Getting Default mail session:
Session session = Session.getDefaultInstance(prop, null);
Composing a new Mail:
Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); message.addReceipient(Message.ReceipientType.To, new InternetAddress(toAddress)); message. addReceipient(Message.ReceipientType.CC, new InternetAddress(ccAddress)); message.setSubject(subjectOftheMail); message.Content(message.toString(), “text/plain”);
Sending the Mail:
After we compose the email we can use the following line of code to send the mail.
Transport.send(message);