Sending Emails with Java
Sending emails using a Java application is quite straightforward, but first, you need to install the JavaMail API and the Java Activation Framework (JAF) on your machine.
You can download the latest version of JavaMail from the Java website. On the right side of the page, there is a Downloads link; click it to download.
You can also download the latest version of JAF (Version 1.1.1) from the Java website.
Alternatively, you can use the download links provided on this site:
Download and unzip these files. In the newly created top-level directory, you will find several jar files for these applications. You need to add the mail.jar and activation.jar files to your CLASSPATH.
If you are using a third-party mail server like QQ's SMTP server, you can refer to the complete example with user authentication at the bottom of the article.
Sending a Simple Email
Below is an example of sending a simple email. Assume that your local host is connected to the network.
SendEmail.java File Code:
// File name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID
String to = "[email protected]";
// Sender's email ID
String from = "[email protected]";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object
MimeMessage message = new MimeMessage(session);
// Set From: header field
message.setFrom(new InternetAddress(from));
// Set To: header field
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Set the actual message
message.setText("This is the actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run this program to send a simple email:
$ java SendEmail
Sent message successfully....
If you want to send an email to multiple recipients, use the following method to specify multiple recipient IDs:
void addRecipients(Message.RecipientType type,
Address[] addresses)
throws MessagingException
Here is the description of the parameters:
- type: To be set as TO, CC, or BCC, where CC stands for carbon copy and BCC stands for blind carbon copy. Example: Message.RecipientType.TO
- addresses: This is an array of email IDs. When specifying email IDs, you will need to use the InternetAddress() method.
Sending an HTML Email
Below is an example of sending an HTML email. Assume your localhost is connected to the network.
Similar to the previous example, except we use the setContent() method with the second parameter set to "text/html" to specify the content to be HTML.
SendHTMLEmail.java File Code:
// File name SendHTMLEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendHTMLEmail
{
public static void main(String [] args)
{
// Recipient's email ID
String to = "[email protected]";
// Sender's email ID
String from = "[email protected]";
// Specify the host for sending the email
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field
message.setFrom(new InternetAddress(from));
// Set To: header field
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send HTML message, can insert HTML tags
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run this program to send an HTML email:
$ java SendHTMLEmail
Sent message successfully....
Sending an Email with Attachments
Compile and run this program to send a simple email:
$ java SendEmail
Sent message successfully....
If you want to send an email to multiple recipients, use the following method to specify multiple recipient IDs:
void addRecipients(Message.RecipientType type,
Address[] addresses)
throws MessagingException
Here is the description of the parameters:
- type: To be set as TO, CC, or BCC, where CC stands for carbon copy and BCC stands for blind carbon copy. Example: Message.RecipientType.TO
- addresses: This is an array of email IDs. When specifying email IDs, you will need to use the InternetAddress() method.
Sending an HTML Email
Below is an example of sending an HTML email. Assume your localhost is connected to the network.
Similar to the previous example, except we use the setContent() method with the second parameter set to "text/html" to specify the content to be HTML.
SendHTMLEmail.java File Code:
// File name SendHTMLEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendHTMLEmail
{
public static void main(String [] args)
{
// Recipient's email ID
String to = "[email protected]";
// Sender's email ID
String from = "[email protected]";
// Specify the host for sending the email
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field
message.setFrom(new InternetAddress(from));
// Set To: header field
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Send HTML message, can insert HTML tags
message.setContent("<h1>This is actual message</h1>",
"text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run this program to send an HTML email:
$ java SendHTMLEmail
Sent message successfully....
Sending an Email with Attachments
Below is an example of sending an email with an attachment. Assume your local host is already connected to the network.
SendFileEmail.java File Code:
// File name SendFileEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendFileEmail
{
public static void main(String [] args)
{
// Recipient's email ID
String to = "[email protected]";
// Sender's email ID
String from = "[email protected]";
// Specify the host for sending the email as localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Set mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field
message.setFrom(new InternetAddress(from));
// Set To: header field
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Message
messageBodyPart.setText("This is message body");
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Attachment part
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message
message.setContent(multipart );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Compile and run your program to send an email with an attachment.
$ java SendFileEmail
Message sent successfully....
User Authentication Section
If you need to provide a username and password to the email server for user authentication purposes, you can achieve this by setting up as follows:
props.put("mail.smtp.auth", "true");
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
The rest of the email sending mechanism remains consistent with the above.
Example of Email Sending with Username and Password Verification:
This example uses the QQ Mail server as an illustration. You need to enable POP3/SMTP service in the QQ Mail settings under "Settings" => "Account," as shown in the image below:
QQ Mail uses an authorization code to set the password:
Java code is as follows:
SendEmail2.java File Code:
// Example of email sending with username and password
// File name: SendEmail2.java
// This example uses QQ Mail, and you need to set it up in the QQ Mail backend
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail2
{
public static void main(String [] args)
{
// Recipient's email ID
String to = "[email protected]";
// Sender's email ID
String from = "[email protected]";
// Specify the mail server as smtp.qq.com
String host = "smtp.qq.com"; // QQ Mail server
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
// Get the default session object
Session session = Session.getDefaultInstance(properties, new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("[email protected]", "QQ Mail authorization code"); // Sender's email username, authorization code
}
});
try{
// Create a default MimeMessage object
MimeMessage message = new MimeMessage(session);
// Set From: header field
message.setFrom(new InternetAddress(from));
// Set To: header field
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Set the message body
message.setText("This is the actual message");
// Send the message
Transport.send(message);
System.out.println("Sent message successfully....from tutorialpro.org"); } catch (MessagingException mex) { mex.printStackTrace(); } } ```