Sunday 2 December 2012

Java Email

Posted by Naveen Katiyar On 09:33 No comments

This java tutorial is to send email in java using Gmail. Example java email program will use Gmail SMTP server to send mail.
There is not much involved to discuss as javamail api takes care of everything. It is all about just using the JavaMail api. By every release, javamail api is getting sophisticated and so it is an easy job.

I have used JavaMail API version 1.4.5 and should add two jars as dependency for sending email mailapi.jar and smtp.jar



  • My example program uses Gmail SMTP server.
  • Mail authentication is set to true and need to give sender’s email and password. That is, we cannot send email anonymously.
  • In the program you can modify it to send to multiple To emails.
  • Sample uses HTML email as content type.
  • You can add email attachment to emailMessage.
  • To send email and test the program, just change fromUser and fromUserEmailPassword. Yes it is as simple as that.



package mypack;

import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMail {
public void sendMail() {
String msg="hello world,I m sending mail using java mail api.";
String sub = "java mail";
String to = "abc@hotmail.com";// change accordingly
String to1 = "xyz@gmail.com";// change accordingly

// Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"pqr@gmail.com","password");//change accordingly
}
});

// compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("haritrajput@gmail.com"));// change
// accordingly
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to1));
message.setSubject(sub);
message.setText(msg);

// send message
Transport.send(message);

System.out.println("message sent successfully");

} catch (MessagingException e) {
throw new RuntimeException(e);
}

}
}


0 comments: