Send email with attachment using JavaMail API

We are explaining here an example of sending email with attachment using JavaMail API.

Steps of sending email with attachment using JavaMail API:

    1. Get a session instance from getDefaultInstance() or getInstance() method of Session class.
    2. Create a message we have to pass session object in MimeMessage class constructor.
    3. Use the InternetAddress class to set the information of sender and recipient.
    4. Create the MimeBodyPart object and set actual message.
    5. Create DataHandler object and set attachment in it.
    6. Create a new MimeBodyPart object and set DataHandler object in it.
    7. Create a MimeMultipart object and set MimeBodyPart objects in it.
    8. Set the multipart object in the message object.
    9. Use send() method of javax.mail.Transport class to send the message.


import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
 * This class is used to send email with attachment.
 * @author w3spoint
public class SendEmailWthAttachment  { 
 final String senderEmailId = "[email protected]";
 final String senderPassword = "****";
 final String emailSMTPserver = "";
public SendEmailWthAttachment (String receiverEmail, 
		String subject, String messageText, 
		String fileName, String filePath) {		
    Properties props = new Properties();
	props.put("mail.smtp.auth", "true");
	props.put("", emailSMTPserver);
  try { 			
	Authenticator auth = new SMTPAuthenticator();
	Session session = Session.getInstance(props, auth);
	Message message = new MimeMessage(session);
	message.setFrom(new InternetAddress(senderEmailId));
	MimeBodyPart messageBodyPart1 = new MimeBodyPart(); 
	MimeBodyPart messageBodyPart2 = new MimeBodyPart(); 
	DataSource source = new FileDataSource(filePath); 
	messageBodyPart2.setDataHandler(new DataHandler(source));
	Multipart multipart = new MimeMultipart();   
	System.out.println("Email send successfully."); 
  } catch (Exception e) {
    System.err.println("Error in sending email.");
private class SMTPAuthenticator extends 
   javax.mail.Authenticator {
    public PasswordAuthentication 
    getPasswordAuthentication() {
        return new PasswordAuthentication(senderEmailId, 
public static void main(String[] args) {
	new SendEmailWthAttachment ("[email protected]", 
			"Test Email", "Hi,\n\n This is a test email " +
			"with attachment.", "D:\\test.txt", "test.txt");


Email send successfully.

Download this example.
Next Topic: Send HTML content with example.
Previous Topic: Send email with example.


Please Share