How do I send an email with attachment?

In this example we create a small program to send email with a file attachment. To send message with attachment we need to create an email with javax.mail.Multipart object which basically will contain the email text message and then add a file to the second block, which both of them is an object of javax.mail.internet.MimeBodyPart. In this example we also use the javax.activation.FileDataSource.

package org.kodejava.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

public class SendEmailWithAttachment {
    public static void main(String[] args) {
        SendEmailWithAttachment demo = new SendEmailWithAttachment();

    public void sendEmail() {
        // Defines the E-Mail information.
        String from = "[email protected]";
        String to = "[email protected]";
        String subject = "Important Message";
        String bodyText = "This is a important message with attachment.";

        // The attachment file name.
        String attachmentName = "data.txt";

        // Creates a Session with the following properties.
        Properties props = new Properties();
        props.put("", "");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        Session session = Session.getDefaultInstance(props);

        try {
            InternetAddress fromAddress = new InternetAddress(from);
            InternetAddress toAddress = new InternetAddress(to);

            // Create an Internet mail msg.
            MimeMessage msg = new MimeMessage(session);
            msg.setRecipient(Message.RecipientType.TO, toAddress);
            msg.setSentDate(new Date());

            // Set the email msg text.
            MimeBodyPart messagePart = new MimeBodyPart();

            // Set the email attachment file
            FileDataSource fileDataSource = new FileDataSource(attachmentName);

            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(new DataHandler(fileDataSource));

            // Create Multipart E-Mail.
            Multipart multipart = new MimeMultipart();


            // Send the msg. Don't forget to set the username and password
            // to authenticate to the mail server.
            Transport.send(msg, "kodejava", "password");
        } catch (MessagingException e) {

Maven Dependencies


Maven Central Maven Central



  1. Hi, I followed your code and its works for me but I want file name as dynamic, for example user uploaded file as attachment. I am using Struts 1.x. Please help me.

  2. I am getting this error

    javax.mail.MessagingException: Could not connect to SMTP host:, port: 587;
      nested exception is: Connection timed out: connect
        at com.sun.mail.smtp.SMTPTransport.openServer(
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(
        at javax.mail.Service.connect(
        at javax.mail.Service.connect(
        at javax.mail.Service.connect(
        at javax.mail.Transport.send0(
        at javax.mail.Transport.send(
        at com.mail.mailWithAttachment.SendEmailWithAttachment.sendEmail(
        at com.mail.mailWithAttachment.SendEmailWithAttachment.main(
    Caused by: Connection timed out: connect
        at Method)
        at Source)
        at Source)
        at Source)
        at Source)
        at Source)
        at Source)
        at Source)
        at Source)
        at com.sun.mail.util.SocketFetcher.createSocket(
        at com.sun.mail.util.SocketFetcher.getSocket(
        at com.sun.mail.smtp.SMTPTransport.openServer(
        ... 8 more
  3. Hi Vivek,

    Check the connection to using telnet command to see if you can connect to it. Use the following command:

    telnet 578

    If you can connect you should see something like this

    $ telnet 587
    Connected to
    Escape character is '^]'.
    220 ESMTP d89sm3363323pfl.7 - gsmtp
  4. I am unable to execute, throwing exception.

    java.lang.NoSuchMethodError: com.sun.mail.util.TraceInputStream.(Ljava/io/InputStream;Lcom/sun/mail/util/MailLogger;)V
  5. Hi Wayan, Is there any property for compress or zip the file when adding as attachment to the email. Actually I am looking same compression functionality in Apache Camel.

  6. Transport.send(msg, "kodejava", "password");

    Its not allowing username and password here. How we can authenticate this one please help me.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.