Java Email

I have used  Java Mail API 1.4.3. I have added mail.jar as dependency.

  • My example program uses yahoo SMTP server.
  • To use Gmail use 587 gmail smtp port
  • “” as gmail smtp host
  • 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.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMail {

public static void main(String args[]) {
 Properties props = new Properties();

// for gmail

//props.put("mail.smtp.port", "587");
 //props.put("", "");

props.put("", "");// remove this for gmail
 props.put("mail.stmp.user", "");
 //To use TLS
 props.put("mail.smtp.auth", "true");
 props.put("mail.smtp.starttls.enable", "true");
 props.put("mail.smtp.password", "*****");
 Session session = Session.getDefaultInstance(props, new Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
 String username = "";
 String password = "*****";
 return new PasswordAuthentication(username, password);
 String to = "";
 String from = "";
 String subject = "Testing...";
 MimeMessage msg = new MimeMessage(session);
 try {
 msg.setFrom(new InternetAddress(from));
 msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
 msg.setText("yahoo program working...!");
 Transport transport = session.getTransport("smtp");
 } catch (Exception exc) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s