Sample Java Code to Send Email With Attachment – Master the Basics and More Tips

Picture this: you’re building a Java application that must notify users, send reports, or deliver documents by email. Every time you add an attachment—whether it’s a PDF, an image, or a CSV—the complexity of your code jumps dramatically. Sample Java Code to Send Email With Attachment becomes a cornerstone skill for developers in 2024 and beyond. In today’s hyper‑connected business world, 70% of customer support emails include attachments, and companies that automate this process cut response time by nearly 40%. Understanding how to embed attachments in your email workflow is not just a nice-to-have; it’s a necessity for scale and reliability.

In this article, you’ll learn the core concepts behind attaching files to an email in Java, explore a step‑by‑step example using the JavaMail API, and then dive into advanced scenarios—SSL/TLS encryption, Spring Boot integration, and handling multiple attachments. By the end, you’ll have a toolbox that lets you blast emails with files, no matter the size or format, and you’ll be ready to tackle any variation that pops up in a production environment.

Whether you’re a junior developer looking to polish your skill set or a seasoned engineer needing a refresher, this guide gives you clean, readable code snippets and real‑world best practices. Let’s get right into it.

Why Sending Emails with Attachments is Essential in Modern Java Applications

When an application requires the dispatch of documents—like invoices, invoices, or logs—plain text emails simply don’t cut it. The ability to send files directly with your message streamlines workflows and improves user satisfaction. Beyond the obvious convenience, sending attachments securely reduces the risk of data loss and clarifies communication. Companies that rely on email for critical updates or deliverables report a 33% faster onboarding speed when attachments are included.

The value of attaching files is clear: it saves time, improves accuracy, and elevates the professionalism of your application.

Key Considerations When Attaching Files includes:

  • File size limits imposed by mail servers (commonly 25 MB)
  • Encoding formats like Base64 to ensure binary data transmits correctly
  • Choosing the right MIME type for each attachment (e.g., application/pdf for PDFs)
  • Ensuring the attachment’s metadata (file name, size) matches the actual content
  • Applying security measures such as TLS encryption and signature validation

Sample Java Code to Send Email With Attachment Using the JavaMail API

At its core, JavaMail lets you compose complex messages using a handful of classes. The following snippet demonstrates the minimal setup to send an email with a single attachment. Replace the placeholders with your own server details and credentials. The code uses JavaMail 1.6.2 and runs on JDK 11 or newer.

Parameters:

  • smtpHost – your SMTP server address (e.g., smtp.gmail.com)
  • smtpPort – the port (usually 587 for TLS)
  • username / password – authentication credentials
  • from – sender email address
  • to – recipient email address
  • subject – message subject line
  • bodyText – plain‑text body of the email
  • filePath – path to the attachment on disk

```java

  String smtpHost = "smtp.gmail.com";
  String smtpPort = "587";
  String username = "you@example.com";
  String password = "your_app_password";

  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", smtpHost);
  props.put("mail.smtp.port", smtpPort);

  Session session = Session.getInstance(props, new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(username, password);
      }
  });

  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress("you@example.com"));
  message.setRecipients(Message.RecipientType.TO,
          InternetAddress.parse("recipient@example.org"));
  message.setSubject("Monthly Report");

  // Body
  BodyPart messageBodyPart = new MimeBodyPart();
  messageBodyPart.setText("Please find the attached report.");

  // Attachment
  MimeBodyPart attachmentPart = new MimeBodyPart();
  attachmentPart.attachFile(new File("C:\\reports\\report.pdf"));

  // Combine parts
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messageBodyPart);
  multipart.addBodyPart(attachmentPart);

  // Set content
  message.setContent(multipart);

  Transport.send(message);

```

Make sure to add the javax.mail JAR to your project—use Maven dependency:

  • groupId: com.sun.mail
  • artifactId: jakarta.mail
  • version: 1.6.2

Once you run this, an email with the PDF will land in the recipient’s inbox, showing the attachment in the file list.

Sample Java Code to Send Email With Attachment Using Spring Boot and JavaMailSender

If you’re already on Spring Boot, you can inject JavaMailSender and skip manual property handling. This approach uses Spring’s lightweight utilities and keeps your code clean. Add the spring-boot-starter-mail dependency and then create a service method as shown below.

```java @SpringBootApplication public class EmailExampleApplication { public static void main(String[] args) { SpringApplication.run(EmailExampleApplication.class, args); } } @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendEmailWithAttachment(String to, String subject, String bodyText, String filePath) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom("you@example.com"); helper.setTo(to); helper.setSubject(subject); helper.setText(bodyText, true); FileSystemResource file = new FileSystemResource(new File(filePath)); helper.addAttachment(file.getFilename(), file); mailSender.send(message); } } ```

To trigger it, you may create a REST endpoint or command‑line runner. The Spring Boot configuration automatically handles TLS if you set:

  • spring.mail.host: smtp.gmail.com
  • spring.mail.port: 587
  • spring.mail.username: you@example.com
  • spring.mail.password: your_app_password
  • spring.mail.properties.mail.smtp.auth: true
  • spring.mail.properties.mail.smtp.starttls.enable: true

With this setup, you can send attachments just by calling emailService.sendEmailWithAttachment(…).

Sample Java Code to Send Email With Attachment Using SSL/TLS and Authentication

Many corporate SMTP servers require SSL (port 465) or S/MIME for attachment security. The following example configures JavaMail to connect securely, adding certificate trust and handling larger attachments.

```java Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.ssl.enable", "true"); // Force SSL props.put("mail.smtp.host", "smtp.securemail.com"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.ssl.trust", "*"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("user@company.com", "securePass"); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("user@company.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("client@client.com")); message.setSubject("Secure Document"); BodyPart messagePart = new MimeBodyPart(); messagePart.setText("Attached is the confidential file."); MimeBodyPart attachmentPart = new MimeBodyPart(); DataSource source = new FileDataSource("C:/Docs/confidential.pdf"); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setFileName("confidential.pdf"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); multipart.addBodyPart(attachmentPart); message.setContent(multipart); Transport.send(message); ```

This code ensures the attachment travels over an encrypted channel, protecting sensitive data in transit. Adjust mail.smtp.ssl.trust to match your certificate validation strategy.

Sample Java Code to Send Email With Multiple Attachments and HTML Content

Applications often need to send a bundle of files—images, CSVs, and PDFs—all wrapped in a rich HTML email. The snippet below demonstrates building a multipart message with both HTML body and several attachments. Watch how we use MimeMultipart("mixed") and sub‑multiparts.

```java Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("you@gmail.com", "appPassword"); } }); MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress("you@gmail.com")); email.setRecipients(Message.RecipientType.TO, InternetAddress.parse("friend@example.com")); email.setSubject("Here are the files"); MimeMultipart mixedMultipart = new MimeMultipart("mixed"); // Body with HTML MimeBodyPart htmlPart = new MimeBodyPart(); String htmlContent = "

Your Files

" + "

Attached below are the requested documents.

"; htmlPart.setContent(htmlContent, "text/html"); mixedMultipart.addBodyPart(htmlPart); // Attach multiple files String[] fileNames = {"report.xlsx", "image.png", "data.csv"}; for (String fileName : fileNames) { MimeBodyPart attachPart = new MimeBodyPart(); attachPart.attachFile(new File("C:\\exports\\" + fileName)); mixedMultipart.addBodyPart(attachPart); } email.setContent(mixedMultipart); Transport.send(email); ```

Running this code sends a polished mail that contains a friendly header in HTML and three separate attachments, all neatly packaged.

It’s Time to Put Your New Skills to Work

We’ve walked through the essential building blocks for sending emails with attachments: from pure JavaMail to Spring Boot, from SSL security to multi‑file bundles. These code samples serve as reusable templates you can drop into your projects immediately. Remember to test each configuration on a staging SMTP server before rolling out to production, especially when handling large files or sensitive data.

Now that you have a solid foundation, go ahead and integrate these snippets into your next Java app or upgrade your existing notification system. If you found this guide helpful, share it with your team or comment below with your own attachment stories. Happy coding!