Updated February 15, 2023
Introduction to Deleting Email in Java
The following article provides an outline for Deleting Email in Java. Delete email in Java allows you to delete emails as well as send, forward, and receive them. It allows you to delete a specific message by using the setFlag option of the Message class java mail APIs, which is one of the email sending stages. Java mail APIs is one of the email sending stages before reading the data to send or receive with the help of these jars mail.jar and activation.jar to carry out the java operations.
Key Takeaways
- In application, we are using Gmail and other mail servers.
- We are leveraging the IMAP protocol to show the unread emails from the inbox.
- The first unread email was then deleted.
- We can properly observe the outcome once the application has finished running and we have opened the inbox.
- POP protocol only allows for message deletion.
Overview of Deleting Email
Deleting emails in Java has the option to delete emails as well as send, forward, and receive them. It accepts to delete a specific message that utilizes the setFlag option like function of the Message class. The session object is used to Open the folder object after creating it and then to connect the store object to the current host machine by using the setFlag method and then obtain the message to be deleted. Working with the Flags connected to the messages is necessary for message deletion. There are several flags for various states and some of which are system-defined and others that are user-defined. The inner class Flags always define the predefined flags.
How to Delete Email Programmatically in Java?
The email can be deleted in 4 steps altogether:
1. Session object
The Session object maintains data or modifies settings related to a user session. All pages in a single application can access variables contained in a session object, which holds data about a single user. Name, id, and preferences are examples of information frequently saved in session variables.
2. Connect to the current host and construct the storage object
To export design-time metadata into a database Integration instance, and should build the storage URL to specify and create a storage bucket (if one doesn’t already exist). To migrate the instance, we must specify this URL later on during the configuration procedure. Then utilizing the Application Migration Service will automatically complete these tasks.
3. To make the folder object, then launch it
There is no requirement that a Folder object received from a Storage really exists in the backend store. The folder’s existence is checked using the exists method. A Folder is created with the create method. Initially, a folder is in closed condition. The documentation for several methods makes mention of the fact that they are valid in this condition. Calling a Folder’s ‘open’ function opens it. All Folder methods are functional in this state with the exception of open and delete.
4. Using the setFlag method, obtain the message to be deleted
To access Gmail or other mail servers. Using IMAP as the protocol, we are displaying unread emails from the inbox. After which you delete the first unread email. If we open the inbox after the program has finished running, we can accurately see the outcome.
Flags are mainly supported to declare the predefined flags an inner class:
- Flags.Flag.Answered
- Flags.Flag.Deleted
- Flags.Flag.Recent
- Flags.Flag.User
The above flags are some frequent usages in different states for both system-defined and user-defined emails.
Deleting Email API
To get the session object is the first step to proceed with the delete operation after that we can create the store object. To make sure the store object is connected to localhost or internal mail server credentials additionally we can get the store by using getStore() method to retrieve the protocol like Imap, Pop3, SMTP, etc. The folder object is the next way for accessing the emails like Inbox or any other personal or public access folders.
By using the Message[] array we can retrieve the messages from the specific folder. For that using getMessages() method is the path to retrieve it. We know that Flags is the most important role to delete the required messages. Here we can use the method called setFlag(FLAGS.Flag.DELETED, boolean) these conditions are validated the messages and set the flag as deleted on the required folder.
Deleting Mail Server
In java, we can use the Interface called MailServerManager to implement the java default classes like AbstractMailServerManager, OFBizMailServerManager, and XMLMailServerManager. With the help of String[] array which denotes the server_types that allowed to create, update, and deleted the servers. The create(MailServer instance) for creating the mail server with instance id long type. Here we can delete the server instance id like delete(java.lang.Long mailServerId) with void type.
Example of Deleting Email in Java
Given below is the example mentioned:
Code:
package TestNG;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class NewTest {
public static void deletemail(String hst, String stype, String emailuser,
String passwd)
{
try
{
Properties props = new Properties();
props.put("mail.store.protocol", "pop3");
props.put("mail.pop3s.host", hst);
props.put("mail.pop3s.port", "995");
props.put("mail.pop3.starttls.enable", "true");
Session sess = Session.getDefaultInstance(props);
Store st = sess.getStore("pop3s");
st.connect(hst, emailuser, passwd);
Folder fld = st.getFolder("INBOX");
fld.open(Folder.READ_WRITE);
BufferedReader rd = new BufferedReader(new InputStreamReader(
System.in));
Message[] msgs = fld.getMessages();
System.out.println("msgs.length---" + msgs.length);
for (int i = 0; i < msgs.length; i++) {
Message ms = msgs[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Email Subject: " + ms.getSubject());
System.out.println("From: " + ms.getFrom()[0]);
String sub = ms.getSubject();
System.out.print("Do you want to delete this message [y/n] ? ");
String res = rd.readLine();
if ("Y".equals(res) || "y".equals(res)) {
ms.setFlag(Flags.Flag.DELETED, true);
System.out.println("Marked DELETE for message: " + sub);
} else if ("n".equals(res)) {
break;
}
}
fld.close(true);
st.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
}
}
public static void main(String[] args) {
String gmailhost = "pop.gmail.com";
String mailStoreType = "pop3";
String username = "[email protected]";
String password = "xodbizaoiqijifre";
deletemail(gmailhost, mailStoreType, username, password);
}
}
Output:
Explanation:
- In the above example, we imported mail and io packages and their default classes, methods, etc.
- Then using Properties class, we can configure the mail server and other details.
- Using required classes and their methods we can perform mail operations like create, delete, etc.
- For loop to iterate the mail data and use a try-catch block to get the mail exceptions.
- We can call the method in the main function to execute the operations.
Conclusion
Along with the ability to send, forward, and receive emails, this option also exists. The setFlag method of the Message class can be used to delete a specific message. To make sense, you need to be familiar with the email-sending steps of the JavaMail API. Only message deletion in Java email is supported by the POP protocol. Connect to the host that is now active before creating the storage object to get the session object. Take the message to be destroyed, create the folder object, and then launch it using the setFlag function.
FAQs
Given below are the FAQs mentioned:
Q1. What is deleting email in java?
Answer: We have the option to delete emails as well as send, forward, and receive them. To delete a specific message, utilize the setFlag function of the Message class. Learn the JavaMail API’s email-sending stages before reading this example to make sense of it.
Q2. What protocol do we use to delete the email in java?
Answer: POP protocol is used to support only messages deleted in java mails.
Q3. How to delete the email in java?
Answer: To Get the session object first then, connect to the current host and construct the storage object. Make the folder object, then launch it. Using the setFlag method, obtain the message to be deleted.
Recommended Articles
This is a guide to Deleting Email in Java. Here we discuss the introduction, how to delete email programmatically in java, deleting email API & examples. You may also have a look at the following articles to learn more –