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 contains 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.example.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 = "";
        String to = "";
        String subject = "Important Message";
        String bodyText = "This is a important message with attachment.";

        // The attachment file name.
        String attachmentName = "D:/Temp/hello.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");
        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", "********");
        } catch (MessagingException e) {

Maven Dependencies

<!-- -->
<!-- -->


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ☕ or 🍵


  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

Leave a Reply