Send email with attachment in Java using Gmail


In this example, we are going to send an email with attachment in Java program via Gmail server. JavaMail API provides the classes like…

Multipart – Multipart is a container that holds multiple body parts. Multipart provides methods to retrieve and set its subparts. Multipart also acts as the base class for the content object returned by most Multipart DataContentHandlers.

BodyPart – BodyPart implements the Part interface. Thus, it contains a set of attributes and a content.

MimeBodyPart – This class represents a MIME body part. It implements the BodyPart abstract class and the MimePart interface. MimeBodyParts are contained in MimeMultipart objects.

Steps for Code

1- Get the Session.
2- Create MimeMessage object and set From, To, Subject in the message.
3- Create a MimeMultipart object.

Multipart multipart = new MimeMultipart();

4- Add message in email as follows.

BodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("This email has an attachement. Please find the attach file. Thank You :)");
multipart.addBodyPart(bodyPart);

5- Add the attachment as follows.

MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.attachFile(new File("F:/WebSparrow/logo/ws.jpg"));
multipart.addBodyPart(mimeBodyPart);

6- Set the multipart in the message as follow.

message.setContent(multipart);

7- Send the message using the Transport object.

Transport.send(message);

Check the full example

SendEmailWithAttachment.java
package org.websparrow;

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

import javax.mail.BodyPart;
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 SendEmailWithAttachment {
	public static void main(String[] args) throws IOException {

		final String username = "[email protected]";
		final String password = "xxxxxxx";

		// setting gmail smtp properties
		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");

		// check the authentication
		Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("[email protected]"));

			// recipients email address
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));

			// add the Subject of email
			message.setSubject("JavaMail API Test");

			Multipart multipart = new MimeMultipart();

			// add the body message
			BodyPart bodyPart = new MimeBodyPart();
			bodyPart.setText("This email has an attachement. Please find the attach file. Thank You");
			multipart.addBodyPart(bodyPart);

			// attach the file
			MimeBodyPart mimeBodyPart = new MimeBodyPart();
			mimeBodyPart.attachFile(new File("F:/WebSparrow/logo/ws.jpg"));
			multipart.addBodyPart(mimeBodyPart);

			message.setContent(multipart);

			Transport.send(message);

			System.out.println("Email Sent Successfully");

		} catch (MessagingException e) {
			e.printStackTrace();

		}
	}
}

Output:

Email Sent Successfully.

Note: You may face the javax.mail.AuthenticationFailedException exception. To resolve this check this tutorial javax.mail.AuthenticationFailedException


Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.