Basic Java – 20 || Sending Email with attachment using Java (Part-2).

In the last chapter, we have learned sending email using Java. In this chapter, we will go a little in-depth and will learn a few important things like multiple recipients, attachments, marking cc or bcc, etc.

Sending email using java.

Key Highlights in this chapter

  1. Single recipient or email id for To field
    • message.setRecipient(RecipientType.TO, new InternetAddress(recieverID));
  2. Multiple recipients or email id for CC or BCC field
    • message.setRecipients(RecipientType.CC, recipients);
  3. Use of multiple instances of Multipart Class for Message instance
    • BodyPart contentPart = new MimeBodyPart();
    • MimeBodyPart attachementPart=new MimeBodyPart();
  4. Implement HTML content in the email body part
    • contentPart.setContent(String htmlCode, “text/html”);
  5. Adding attachment to the email
    • attachementPart.attachFile(“.\test-output\emailable-report.html”);

Sending email with attachment

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
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.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

 * @author ashok.kumar
public class Mailer2 {

	 * @param args
	 * @throws IOException 
	 * @throws MessagingException
	public static void main(String[] args) throws IOException {
		System.out.println("Step #1: Getting email information...");
		String userName = "";
		String password = "xxxxxx";
		String recieverID = "";

		System.out.println("Step #2: Getting email server details...");
		Properties prop = new Properties();
		prop.put("", "");
		prop.put("mail.smtp.port", "587");
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.smtp.starttls.enable", "true");

		System.out.println("Step #3: Creating session to send email...");
		Session session = Session.getInstance(prop, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);


		System.out.println("Step #4: Preparing message content for email...");
		Message message = new MimeMessage(session);
		try {
			message.setSubject("Test Report 2: with attachment");

			// Add email id for FROM field.
			message.setFrom(new InternetAddress(""));

			// Add single recipient email id for TO field
			message.setRecipient(RecipientType.TO, new InternetAddress(recieverID));

			// Adding Multiple recipient email ids for CC field
			Address[] recipients = new Address[2];
			recipients[0] = new InternetAddress("");
			recipients[1] = new InternetAddress("");
			message.setRecipients(RecipientType.CC, recipients);

			Multipart mp = new MimeMultipart();

			// Creating first body part of the Email with content.
			BodyPart contentPart = new MimeBodyPart();
			// This will add sample text in email body.
			contentPart.setText("This is body text without HTML.");
			// Add HTML content to the email body.
			// When setContent() called setText() will not work
			String htmlCode = "<h1>This is HTML Content</h1><br><b>This is second line in bold.</b>";
			contentPart.setContent(htmlCode, "text/html");
			// Creating second body part of the email with attachment.
			System.out.println("Step #5: Preparating attachment in the email...");
			MimeBodyPart attachementPart=new MimeBodyPart();

			// Adding both bodyparts objects into Multipart object.


			System.out.println("Step #6: Sending email in-progress...");
			System.out.println("Step #7: Email sent successfully.");

		} catch (MessagingException e) {
			System.out.println("Step #7: Email sending error. May be you are not connected to internet...");

Leave a Reply

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

Site Statistics

  • Users online: 0 
  • Visitors today : 6
  • Page views today : 6
  • Total visitors : 51,171
  • Total page view: 70,438

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.