Categories: JavaMail

Replying email in Java Mail API

In this chapter we will see how to reply to an email using JavaMail API.

We can forward the received mail to someone else as we send emails. There are many javamail classes that are used to forward the messages to the destination resource.

Replying email in Java Mail API

For better understanding of this example, learn the steps of sending email using JavaMail API first.

For receiving or sending the email using JavaMail API, you need to load the two jar files:

  • mail.jar
  • activation.jar

Create Java Class

Create a java class file ReplyToEmail, the contents of which are as follows:

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
 
public class ReplyToEmail {
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  final String username="admin@dineshonjava.com";
  final String password="******";
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(username,password);
    }
   });
  try {
  Store store = session.getStore("imaps");  
  store.connect("imap.gmail.com",username, password);  
  
  //Create a Folder object and open the folder  
  Folder folder = store.getFolder("inbox");  
  folder.open(Folder.READ_ONLY);  
     Message message = folder.getMessage(10);  
    // Get all the information from the message  
    String from = InternetAddress.toString(message.getFrom());  
    if (from != null) {  
   System.out.println("From: " + from);  
    }  
    String replyTo = InternetAddress.toString(message.getReplyTo());  
    if (replyTo != null) {  
   System.out.println("Reply-to: " + replyTo);  
    }  
    String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));  
    if (to != null) {  
   System.out.println("To: " + to);  
    }  
    
    String subject = message.getSubject();  
   if (subject != null) {  
  System.out.println("Subject: " + subject);  
   }  
   Date sent = message.getSentDate();  
   if (sent != null) {  
  System.out.println("Sent: " + sent);  
   }  
   System.out.println(message.getContent());  
   
   // compose the message to forward  
   Message message2 = new MimeMessage(session);  
    message2= (MimeMessage) message.reply(false);
   message2.setSubject("RE: " + message.getSubject());  
   message2.setFrom(new InternetAddress(from));  
   message2.setReplyTo(message.getReplyTo());

   message2.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
   
   // Create your new message part  
   BodyPart messageBodyPart = new MimeBodyPart();  
   messageBodyPart.setText("Oiginal message:nn");  
   
   // Create a multi-part to combine the parts  
   Multipart multipart = new MimeMultipart();  
   multipart.addBodyPart(messageBodyPart);  
   
   // Create and fill part for the forwarded content  
   messageBodyPart = new MimeBodyPart();  
   messageBodyPart.setDataHandler(message.getDataHandler());  
   
   // Add part to multi part  
   multipart.addBodyPart(messageBodyPart);  
   
   // Associate multi-part with message  
   message2.setContent(multipart);  
   
   // Send message  
   Transport.send(message2);  
   
   System.out.println("message replied successfully ....");  
   } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
}

Compile and Run

Now that our class is ready, let us compile the above class. I’ve saved the class ReplyToEmail.java to directory : D:Javasmailapi. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class

Verify Output

You should see the following message on the command console:
From: Anonymous <noreply-comment@blogger.com>
Reply-to: Anonymous <noreply-comment@blogger.com>
To: admin@dineshonjava.com
Subject: [Dinesh on Java] New comment on Writing First AspectJ Program in Spring
: Chapter ….
Sent: Wed Dec 19 10:29:12 IST 2012
javax.mail.internet.MimeMultipart@1afebc9
message replied successfully ….

 

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago