Java Mail API (Application Programming Interface) can be used to send email through Java programs. Here, in this blog code examples are provided with explanation on how to send email using smtp protocol with gmail server.
Dependency Jar:
java-mail-1.4.4.jar can be downloaded from any site. 1.4.4 is the java mail api version referred by below program for execution.
Email Code:
Below steps are just the guidance for any programmer and it is not mandatory to follow same methodical approach.
- Create SendEmail.java with main method and sendEmail method. sendEmail method accepts below parameters and implement logic.
# fromEmail - String
# toEmail - String array (For more than one recipient).
# subject - String (Contains email subject)
# messageContent - String (Contains email message body content)
- Load all properties required for sending email.
Properties properties = new Properties();
properties.put("mail.smtp.host","smtp.gmail.com");
properties.put("mail.smtp.port", 587);
properties.put("mail.smtp.auth",true);
properties.put("mail.smtp.starttls.enable",true);
- Creates Javax mail Session object instance by passing required authentication information or default information as required by email server. Sending email through gmail smtp server, need to pass across an authentication email user and password.
session = Session.getDefaultInstance(properties,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(<Email User ID>, <Email Password>);
}
});
- Create MimeMessage and add receipent, subject and message content. Using Transport class send email by passing MimeMessage instance as parameter.
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmail));
// Set To: header field of the header.
for(int index=0; index < to.length; index++) {
message.addRecipient(Message.RecipientType.TO,new InternetAddress(toEmail[index]));
}
// Set Subject: header field
message.setSubject(subject);
// Set Message Content
message.setContent(messageContent, "text/html");
// Send message
Transport.send(message);
- In main method, create instance of SendEmail class and call sendEmailMethod with parameters.
// Sender's email ID needs to be mentioned
String from = "<Provide from Email id>";
// Recipient's email ID needs to be mentioned in an array
String[] to = {"<Receipent 1 Email ID", "Receipent 2 Email ID"};
// Email Subject
String subject = "This is the Subject Line!";
// Email Message Content
String messageContent = "<h1>This is the actual Message</h1>";
// Call Email send method.
SendEmail se = new SendEmail();
try {
se.sendEmailMessage(from, to, subject, messageContent);
} catch(Exception excep) {
excep.printStackTrace();
}
- Include java-mail-1.4.4.jar in class path for compiling and executing the program in command line.
No comments:
Post a Comment