If you want to integrate email application in your java program or like me you want to reinvent wheel for curiosity, you can use Java mail API.
This API is available on Oracle website and free to download. So you can download it and add to your application to facilitate it with built in email.
This API is really simple to use and with few lines of coding you can send/receive email to/from different accounts.
For this purpose I have written a really simple application which sends an email from Windows live/hotmail account to another email address.
Here is the code :
package email;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class Email {
public static void main(String[] args) {
final String username = "YOUR EMAIL ADDRESS";
final String password = "YOUR PASSWORD"
Properties props = new Properties();
// Setting of Live account. Setting of Gmail is commented
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.live.com");
props.put("mail.smtp.port", "587");
// Gmail Setting
//props.put("mail.smtp.host", "smtp.gmail.com");
//props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("YOUR EMAIL ADDRESS"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("YOUR RECIEVER EMAIL ADDRESS"));
message.setSubject("SUBJECT");
message.setText("Hello Dear reciever, \n \n This is test email from JAVA Application!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
All explanation is given inside of the code where it’s necessary. Otherwise, the code is pretty self-explanatory. The only comment to add is that every mail server has its own unique setting which is needed to be set at the setting part. Here for example I used Windows live/Hotmail setting and additionally I put Gmail account setting in comment part.
This API is very powerful and you also can attach file from the application or design application to notice user when an email arrives and so on.
I have plan to write about mentioned features in another post and the above code is just sample about how sending email is working in Java.