Java Code to Send Email with Attachment - onlyxcodes

Sunday, 13 February 2022

Java Code to Send Email with Attachment

This article will teach you how to develop Java code that will send an email with an attachment.


The most frequent and essential requirement for most applications is to send an email. Java Mail API is a platform and standard protocol platform for developing mail and messaging applications.


You'll find detailed guidelines on how to set up JavaMail in your Java application and use the JavaMail API to create and send emails using the SMTP protocol in this source code.


You'll find detailed guidelines on how to set up JavaMail in your Java application and use the JavaMail API to create and send emails using the SMTP protocol in this source code.


To send emails, we'll use a Gmail account. "smtp.gmail.com" is the SMTP server's host address, and the port is "465." For sending emails, the JavaMail API supports both TLS and SSL authentication.


Let's start this tutorial is very easy.


java code to send email with attachment - javax.mail example

Prerequisites

STS (Spring Tool Suite)


Java 8


Create New Maven Project

Step 1: Open STS (Spring Tool Suite) and choose File - New - Other. A wizard will appear; pick the Maven folder, then the Maven project, and then click the Next button.


Look at the below two figures.


open sts (spring tool suite) and choose file - new - other

Select Maven Project


select maven project - java send email gmail

Step 2: Click the Next button to open a new Maven project window.


Note: In this phase, select the drive location where you want to create this project by clicking the Browse button.


select drive location where you want to create project - email application in java with source code

Step 3: Again new Maven window opens of Archetype. Scroll down and select "org.apache.maven.archetypes maven.archetype-quickstart 1.1".


After selecting click on the Next button.


select archetype - java send email without smtp server

Step 4: In this step, we write our project description look I have mentioned below copy it, and paste this.


Group Id: com.onlyxcodes


Artifact Id: Email_Send_Attachment


Package: com.onlyxcodes.app


write your project description - java program to send email using outlook

Step 5: See the full directory structure below with the App class and pom.xml file.


project directory structure of send email in java with attachment - send email in java spring boot

pom.xml

The pom.xml file is located here. Because I'm using Maven, I've included the JavaMail (javax.mail) dependency in this file.


Using the SMTP, POP3, or IMAP protocols, you can send and receive HTML emails with images and attachments using the JavaMail dependency.


You need two mail.jar and activation.jar files if you're not using Maven. Set your CLASSPATH environment to include these jar files.


<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.onlyxcodes</groupId>
  <artifactId>Email_Send_Attachment</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Email_Send_Attachment</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  
	<dependency>
	    <groupId>com.sun.mail</groupId>
	    <artifactId>javax.mail</artifactId>
	    <version>1.6.2</version>
	</dependency>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
  </dependencies>
</project>

Java Main Class File 


App.java


The App.java class file, often known as the default Java program class file, is included in the com.onlyxcodes.app package.


Within this class file, the main method specified 2 separate methods.


  • sendEmailAttachment() - This method contains code to send an email with an attachment file.

  • sendSimpleEmail() - This method contains program to send simple plain text email.

I specified a 'to', a 'from', a subject,' and a message above both methods (email body).


Within this class, I implemented the email send code above two methods and explained each line code.


Send Email with Attachment:


sendEmailAttachment()


This method code sends an attachment file email for example I attach and send an image logo file.


package com.onlyxcodes.app;

import java.io.File;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
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 App 
{
    public static void main( String[] args )
    {
        String message = "Sent Email with Attachment"; // declare our static message
        String subject = "Onlyxcodes Tutorial: Confirmation"; // declare our static subject 
        String to = ""; // enter recipient email address 
        String from = ""; // enter sender email address
        
        sendEmailAttachment(message, subject, to, from); // this method perform to send email with attachment file 
        
        sendSimpleEmail(message, subject, to, from); // this method perform to method send simple email 
    }

    // this method send email with attachment file
	private static void sendEmailAttachment(String message, String subject, String to, String from) 
	{
		
		//Properties class enables us to connect to the host SMTP server
		Properties properties = new Properties();
		
		//Setup host and mail server
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "465");
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.auth", "true");
		
		// get the session object and pass username and password
		Session session = Session.getInstance(properties, new Authenticator() {

			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("sender email", "sender password");
			}
			
		});
		
		try {
			
			MimeMessage msg = new MimeMessage(session); // Create a default MimeMessage object for compose the message
			
			msg.setFrom(from); // adding sender email id to msg object
			
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // adding recipient to msg object
			
			msg.setSubject(subject); // adding subject to msg object
			
			// set image file location
			String path = "C:\\Users\\Public\\Downloads\\onlyxcodes-logo.png";
			
			MimeMultipart mimeMultipart = new MimeMultipart(); // create MimeMultipart object
			
			MimeBodyPart textMime = new MimeBodyPart(); // create first MimeBodyPart object textMime for containing the message
			
			MimeBodyPart fileMime = new MimeBodyPart(); //create second MimeBodyPart object fileMime for containing the file
			
			textMime.setText(message); //sets message to textMime object
			
			File file = new File(path); //Initialize the File and Move Path variable
			fileMime.attachFile(file); //attach image file to fileMime object
			
			//The mimeMmultipart adds textMime and fileMime to the
			mimeMultipart.addBodyPart(textMime);
			mimeMultipart.addBodyPart(fileMime);
			
			msg.setContent(mimeMultipart); // Sets the mimeMultipart the contents of the msg
			
			Transport.send(msg); // Transport class send the message using send() method
			
			// display below message after email sent successfully 
			System.out.println("Email Sent With Attachment Successfully...");
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	// this method send simple email
	private static void sendSimpleEmail(String message, String subject, String to, String from) 
	{
	}
}

Code Explanation:


The protocol responsible for e-mail transmission is SMTP (Simple Mail Transfer Protocol). The specific properties of the host email provider are set using an example of the utility class named Properties. 


These properties allow us to communicate with a host SMTP server, in this example Gmail.


//Properties class enables us to connect to the host SMTP server
Properties properties = new Properties();

SSL-protected communication is enabled by configuring host settings such as authentication, and port number 465 is configured using the Properties object. To set up mail servers, we use the Gmail SMTP server.


//Setup host and mail server
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");

Obtain the session object using the Session.getInstance() method.


PasswordAuthentication: Found in Package javax.mail. It is the Authenticator's username and password holder, class. 


The method getPasswordAuthentication() uses the Authenticator class from the javax.mail package. This approach is used when password authentication is required.


//get the session object and pass username and password
Session session = Session.getInstance(properties, new Authenticator() {

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication("sender email", "sender password");
	}
			
});

Discussion within try/catch block :


To construct the message, you must transmit the Session Object to the MimeMessage class creator.


The MimeMessage msg object will be used to hold data such as from, to, subject, and message body.


The InternetAddress() class represents an email address that contains capabilities for defining an email address.


The MimeMessage class provides some different methods for storing data in an object. I took the following technique in this example.


public void addRecipient(Message.RecipientType type, Address address) – It's used to add the registered address to the recipient's type.


Here is the description of the elements. 


  • type - TO, CC, or BCC would be specified for this. CC contains Carbon Copy here, and Black Carbon Copy is contained by BCC. Example: Message.RecipientType.To for the message. 

  • addresses -This is an e-mail-based ID. We used the above InternetAddress() method to specify email IDs.

MimeMessage msg = new MimeMessage(session); // Create a default MimeMessage object for compose the message
			
msg.setFrom(from); // adding sender email id to msg object
			
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // adding recipient to msg object
			
msg.setSubject(subject); // adding subject to msg object

As you can see, the code specifies the location of an image-logo file in the path variable.


// set image file location
String path = "C:\\Users\\Public\\Downloads\\onlyxcodes-logo.png";

MIMEMultipart was created to tell the people that "I have more than one part."


The MimeMultipart object has several sections, each of which is defined as a BodyPart form, whose subclass, MimeBodyPart, can take a file as its material.


MimeMultipart mimeMultipart = new MimeMultipart(); // create MimeMultipart object

Creates the textMime MimebodyPart object for a message. 


MimeBodyPart textMime = new MimeBodyPart(); // create first MimeBodyPart object textMime for containing the message

Create the fileMime object MimebodyPart to contain our file.


MimeBodyPart fileMime = new MimeBodyPart(); //create second MimeBodyPart object fileMime for containing the image file

Set the message to a textMime object with the message.


textMime.setText(message); //sets message to textMime object

Initialize a file and set the variable path to. Attach the image or file to an object called FileMime.


File file = new File(path); //Initialize the file and Move Path variable
fileMime.attachFile(file); //attach file to fileMime object

Adds parts of both textMime and fileMime to the mimeMultipart object.


//The mimeMmultipart adds textMime and fileMime to the
mimeMultipart.addBodyPart(textMime);
mimeMultipart.addBodyPart(fileMime);

Last sets the content of mimeMultipart as msg.


msg.setContent(mimeMultipart); // Sets the mimeMultipart the contents of the msg

Transport class finally sends an email or message by send() method. 


Transport.send(msg); // Transport class send the message using send() method

Output:


Look how the recipient receives an email with an image logo and the message content in his inbox.


recipient receives an email with an image logo and the message content in his inbox.

Send Simple Plain Text Email:


sendSimpleEmail() 


In this method, compose and send a simple plain text email.


Friends I've gone over the host settings and other highlights of the above email send with attachment codes.


The below code is the same as the above code. 


Look the difference is this code does not contain MimeMultipart and MimeBodyPart.


package com.onlyxcodes.app;

import java.io.File;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
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 App 
{
    public static void main( String[] args )
    {
        String message = "Sent Email with Attachment"; // declare our static message
        String subject = "Onlyxcodes Tutorial: Confirmation"; // declare our static subject 
        String to = ""; // enter recipient email address 
        String from = ""; // enter sender email address
        
        sendEmailAttachment(message, subject, to, from); // this method perform to send email with attachment file 
        
        sendSimpleEmail(message, subject, to, from); // this method perform to method send simple email 
    }

    // this method send email with attachment file
	private static void sendEmailAttachment(String message, String subject, String to, String from) 
	{
	}
	
	// this method send simple email
	private static void sendSimpleEmail(String message, String subject, String to, String from) 
	{
		//Properties class enables us to connect to the host SMTP server
		Properties properties = new Properties();
		
		
		//Setup host and mail server
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "465");
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.auth", "true");
		
		//get the session object and pass username and password
		Session session = Session.getInstance(properties, new Authenticator() {

			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("sender email", "sender password");
			}
			
		});
		
		try {
			
			MimeMessage msg = new MimeMessage(session); // Create a default MimeMessage object for compose the message
			
			msg.setFrom(from); // adding sender email id to msg object
			
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // adding recipient to msg object
			
			msg.setSubject(subject); // adding subject to msg object
			
			msg.setText(message); // adding our message to msg object
			
			Transport.send(msg); // Transport class send the message using send() method
			
			// display below message after email sent successfully
			System.out.println("Simple Email Sent Simple Successfully...");
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}

	}
}

Output:


See the recipient receiving a simple plain email in his inbox.


recipient receiving a simple plain email in his inbox - simple java mail

App.java full code:

package com.onlyxcodes.app;

import java.io.File;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
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 App 
{
    public static void main( String[] args )
    {
        String message = "Sent Email with Attachment"; // declare our static message
        String subject = "Onlyxcodes Tutorial: Confirmation"; // declare our static subject 
        String to = ""; // enter recipient email address 
        String from = ""; // enter sender email address
        
        sendEmailAttachment(message, subject, to, from); // this method perform to send email with attachment file 
        
        sendSimpleEmail(message, subject, to, from); // this method perform to send simple email 
    }

    // this method send email with attachment file
	private static void sendEmailAttachment(String message, String subject, String to, String from) 
	{
		
		//Properties class enables us to connect to the host SMTP server
		Properties properties = new Properties();
		
		//Setup host and mail server
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "465");
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.auth", "true");
		
		// get the session object and pass username and password
		Session session = Session.getInstance(properties, new Authenticator() {

			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("sender email", "sender password");
			}
			
		});
		
		try {
			
			MimeMessage msg = new MimeMessage(session); // Create a default MimeMessage object for compose the message
			
			msg.setFrom(from); // adding sender email id to msg object
			
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // adding recipient to msg object
			
			msg.setSubject(subject); // adding subject to msg object
			
			// set image file location
			String path = "C:\\Users\\Public\\Downloads\\onlyxcodes-logo.png";
			
			MimeMultipart mimeMultipart = new MimeMultipart(); // create MimeMultipart object
			
			MimeBodyPart textMime = new MimeBodyPart(); // create first MimeBodyPart object textMime for containing the message
			
			MimeBodyPart fileMime = new MimeBodyPart(); //create second MimeBodyPart object fileMime for containing the image file
			
			textMime.setText(message); //sets message to textMime object
			
			File file = new File(path); //Initialize the file and Move Path variable
			fileMime.attachFile(file); //attach file to fileMime object
			
			//The mimeMmultipart adds textMime and fileMime to the
			mimeMultipart.addBodyPart(textMime);
			mimeMultipart.addBodyPart(fileMime);
			
			msg.setContent(mimeMultipart); // Sets the mimeMultipart the contents of the msg
			
			Transport.send(msg); // Transport class send the message using send() method
			
			// display below message after email sent successfully 
			System.out.println("Email Sent With Attachment Successfully...");
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	// this method send simple email
	private static void sendSimpleEmail(String message, String subject, String to, String from) 
	{
	
		//Properties class enables us to connect to the host SMTP server
		Properties properties = new Properties();
		
		
		//Setup host and mail server
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "465");
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.auth", "true");
		
		//get the session object and pass username and password
		Session session = Session.getInstance(properties, new Authenticator() {

			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("sender email", "sender password");
			}
			
		});
		
		try {
			
			MimeMessage msg = new MimeMessage(session); // Create a default MimeMessage object for compose the message
			
			msg.setFrom(from); // adding sender email id to msg object
			
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // adding recipient to msg object
			
			msg.setSubject(subject); // adding subject to msg object
			
			msg.setText(message); // adding our message to msg object
			
			Transport.send(msg); // Transport class send the message using send() method
			
			// display below message after email sent successfully
			System.out.println("Simple Email Sent Simple Successfully...");
			
			
		}catch(Exception e) {
			e.printStackTrace();
		}

	}
}

Library Explanation Top to Bottom:


import javax.mail.Authenticator


The authenticator is a class that represents an object that understands how to get authentication for a network connection. It usually does this by asking the user for information.


import java.io.File


The File Class represents the names of files and directories abstractly.


import java.util.Properties


A stable set of properties is represented by the Properties class. The Properties can be retrieved from or stored in a stream.


import javax.mail.Message


This class is a representation of an email message. To send a message, create a subclass of Message (for example, MimeMessage), fill in the properties and content, and transmit the message using the Transport.send method.


import javax.mail.PasswordAuthentication


This class is nothing more than a storage area for a user name and password.


import javax.mail.Session


A mail session is represented by the Session class.


import javax.mail.Transport


This is an abstract class that represents the transport of a message.


import javax.mail.internet.InternetAddress


The RFC822 syntax is used to indicate an Internet email address in this class.


import javax.mail.internet.MimeBodyPart


A MIME body part is specified by this class. The Internet Headers class is used by MimeBodyPart to read and keep the headers of that body part.


import javax.mail.internet.MimeMessage


A MIME-style email message is described by this class. It implements the Mime Part interface and the Message abstract class.


import javax.mail.internet.MimeMultipart


This class is a subclass of the abstract Multipart class that uses MIME data ways.


Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

What do the replaceAll () do in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

How to print each word in new line in Java

Why do we use :: (double colon) in Java

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

How to Replace a Character in a String in Java without using the Replace Method

What are Variable Arguments in Java

Context Switching in Java Thread Example

Java Stream Iterate Example

What Are the 4 types of loops in Java

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad