How to send Email with attachment in Java Eclipse

Hello, in this tutorial, you will learn how to send an email with an attachment using Java Eclipse. The easiest way to do this is by converting the Java project to a Maven project and integrating the JavaMail API.

The Eclipse IDE version used here is – Eclipse IDE for Java Developers, 2021-09 (4.21.0)

You can make use of the Gmail SMTP to carry out this task.

Sending an Email with attachment in Java:

Steps to integrate the JavaMail library into the Maven Project:

  1. Firstly, create a new Java project.
  2. Right-click on the project and go to ‘configure’. Then, click on ‘Convert to Maven Project’ and click on ‘Finish’.
    Right-click on the Project -> Configure -> Convert to Maven Project -> Finish.
  3. After this, you will see an auto-generated pom.xml file under a folder called ‘target’.
  4. Add the following dependency in the pom.xml file, after the </build> tag, to integrate the JavaMail API with your project.
    <dependencies>
        <dependency>
                <groupId>com.sun.mail</groupId>
                <artifactId>javax.mail</artifactId>
                <version>1.6.2</version>
        </dependency>
    </dependencies>
  5. After adding the dependency, save the pom.xml file. After saving, a folder called ‘Maven Dependency’ will get created in the project, which contains the JavaMail library.
  6. In case there is an error while following the above steps, update the Maven project by following the steps given below:
    Right-click -> Maven -> Update project -> Check all boxes -> Click OK.

    As an alternative, you can press ‘Alt + F5’.

  7. Lastly, create a Java class in the project and run the program.

Java program guide:

  1. Get the system properties using the System.getProperties() method of the Properties class.
  2. Set up the email server. Set the SMTP host as smtp.gmail.com, and the port number as 465. Next, set the mail.smtp.ssl.enable and mail.smtp.auth as “true”.
  3. Create a Session object and authenticate the user ID and password. Pass the sender’s Emal ID and password as the parameters to the PasswordAuthentication() method.
  4. Create a MimeMessage object by passing the Session object to it. Set the from address using the setFrom(new InternetAddress(fromID)) method, to address using the addRecipient(Message.RecipientType.TO, new InternetAddress(toID)) method, and the subject of the Email using setSubject(subject) method.
  5. Create a File object to get the required attachment in the given location.
  6. Create 2 MultiBodyPart objects, one to set the attachment file to be sent and the other to set the text of the Email’s body. Use the attachFile() method for the former and the setText() method for the latter.
  7. Next, create a MultiPart object, and attach the file and the text to the object using the addBodyPart() method.
  8. Set the content of the MimeMessage object as the MultiPart object using the setContent() method.
  9. Finally, send the Email (which is the MimeMessage object) using the send() method of the Transport class.

Note:

If there is an Authentication Exception:

  1. Check if the Email ID and password are correct.
  2. Check if the two-Step verification of the sender’s email is turned off.
    https://support.google.com/accounts/answer/1064203?hl=en
    For this program to work, you should not have two-step verification.
  3. Check if you have allowed access to less secure apps. That is, turn ON the less secure app access of your Gmail for this program to work.
    https://support.google.com/accounts/answer/6010255?hl=en

Java Program:

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class sendJavaMail {

    public static void main(String[] args) {
      
        //Recipient's email ID:
        String toID = "toEmailID@gmail.com";
        //Sender's email ID:
        String fromID = "fromEmailID@gmail.com";
        //Sender's Email Password:
        String password = "xxxx";
        //Subject of the Email:
        String subject = "This is the subject";
        //Body of the Email:
        String bodyText = "This is the text of the body";
        //Change the location of the required attachment file, the format can by anything like jpg, png, pdf etc:
        String attachmentLocation = "D:\\file.jpg";
        // Host is Gmail's SMTP
        String host = "smtp.gmail.com";
        //Getting system properties
        Properties pr = System.getProperties();
        
        //Setting up Email server
        pr.put("mail.smtp.host", host);
        pr.put("mail.smtp.port", "465");
        pr.put("mail.smtp.ssl.enable", "true");
        pr.put("mail.smtp.auth", "true");

        //pass the Email and password to the session object
        Session ss = Session.getInstance(pr, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromID, password);
            }
        });

        try {
            MimeMessage mm = new MimeMessage(ss);
            //Set the 'From:' header field
            mm.setFrom(new InternetAddress(fromID));
            //Set the 'To:' header field
            mm.addRecipient(Message.RecipientType.TO, new InternetAddress(toID));
            //Set the 'Subject:' header field
            mm.setSubject(subject);

            MimeBodyPart attachment = new MimeBodyPart();
            MimeBodyPart text = new MimeBodyPart();
            
            //Change the location of the attachment file:
            File file = new File(attachmentLocation);
            attachment.attachFile(file);
            
            //Set the actual message of the Email:
            text.setText(bodyText);

            Multipart mp = new MimeMultipart();
            mp.addBodyPart(text);
            mp.addBodyPart(attachment);
            
            mm.setContent(mp);
            
            System.out.println("sending the Email...");
            //send the mail:
            Transport.send(mm);
            System.out.println("\nEmail sent successfully!!");
            
        } 
        catch (MessagingException | IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

sending the Email...

Email sent successfully!!

Example:

Let,
toID: emailjava9@gmail.com,
fromID: emailjava9@gmail.com,
password: “Insert the password of the sender’s email”,
subject: “Example Java Email”,
bodyText: “Hello, welcome to CodeSpeedy!\nHarry Potter book 1 is attached in this mail\n” and,
attachmentLocation: “D:\\MyDownloads\\HarryPotter.pdf”
send email in java with file
The output of the above example would be:

sending the Email... 

Email sent successfully!!

send email in Java with file attachment

This is how you send an Email with an attachment using Java! Hope this helped!

Also read, Program for reading all emails present in a file in Java

 

Leave a Reply

Your email address will not be published. Required fields are marked *