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
  • “smtp.gmail.com” 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("mail.smtp.host", "smtp.gmail.com");

props.put("mail.smtp.host", "smtp.mail.yahoo.com");// remove this for gmail
 props.put("mail.stmp.user", "joshi_dax@yahoo.in");
 //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() {
 @Override
 protected PasswordAuthentication getPasswordAuthentication() {
 String username = "joshi_dax@yahoo.in";
 String password = "*****";
 return new PasswordAuthentication(username, password);
 }
 });
 String to = "joshi_dax@yahoo.in";
 String from = "joshi_dax@yahoo.in";
 String subject = "Testing...";
 MimeMessage msg = new MimeMessage(session);
 try {
 msg.setFrom(new InternetAddress(from));
 msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
 msg.setSubject(subject);
 msg.setText("yahoo program working...!");
 Transport transport = session.getTransport("smtp");
 transport.send(msg);
 System.out.println("fine!!");
 } catch (Exception exc) {
 System.out.println(exc);
 }
 }
 }
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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