Skip to toolbar

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.io.IOException;
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 = "xxxx@gmail.com";
		String password = "xxxxxx";
		String recieverID = "xxxxx@gmail.com";

		System.out.println("Step #2: Getting email server details...");
		Properties prop = new Properties();
		prop.put("mail.smtp.host", "smtp.gmail.com");
		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("xxxxxx@gmail.com"));

			// 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("xxxxxxx@gmail.com");
			recipients[1] = new InternetAddress("xxxxxx@gmail.com");
			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();
			attachementPart.attachFile(".\\test-output\\emailable-report.html");

			// Adding both bodyparts objects into Multipart object.
			mp.addBodyPart(contentPart);
			mp.addBodyPart(attachementPart);

			message.setContent(mp);

			System.out.println("Step #6: Sending email in-progress...");
			Transport.send(message);
			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...");
			e.printStackTrace();
		}
	}
}

Leave a Reply

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

Site Statistics

  • Users online: 0 
  • Visitors today : 7
  • Page views today : 9
  • Total visitors : 49,354
  • Total page view: 67,933

   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.