Java Sending Email
Java Sending Email
http://www.tuto rialspo int.co m/java/java_se nding _e mail.htm Co pyrig ht © tuto rials po int.co m
T o send an e-mail using your Java Application is simple enoug h but to start with you should have J avaMail API
and J ava Ac tivation Framework (J AF) installed on your machine.
You can download latest version of JavaMail (Version 1.2) from Java's standard website.
You can download latest version of JAF (Version 1.1.1) from Java's standard website.
Download and unzip these files, in the newly created top level directories you will find a number of jar files for
both the applications. You need to add mail.jar and ac tivation.jar files in your CLASSPAT H.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
$ java SendEmail
Sent message successfully....
If you want to send an e-mail to multiple recipients then following methods would be used to specify multiple e-
mail IDs:
type: T his would be set to T O, CC or BCC. Here CC represents Carbon Copy and BCC represents
Black Carbon Copy. Example Message.RecipientType.TO
addresses: T his is the array of email ID. You would need to use InternetAddress() method while
specifying email IDs
T his example is very similar to previous one, except here we are using setContent() method to set content
whose second arg ument is "text/html" to specify that the HT ML content is included in the messag e.
Using this example, you can send as big as HT ML content you like.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
$ java SendHTMLEmail
Sent message successfully....
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
$ java SendFileEmail
Sent message successfully....
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");