1. DELETING MAILS
To delete a message from a folder, the folder must be opened in read_write mode:
inbox.open(Folder.READ_WRITE);
The message deletion is a two-step process. We first set message’s deleted flag to true:
msg.setFlag(Flags.Flag.DELETED, true);
However, setting the deleted flag to true on a message does not remove it from the folder. Instead it marks the message as deleted. The message is actually deleted when expunge() method on the folder is invoked.
inbox.expunge();
Alternatively, close the folder using its close() method passing the argument true.
inbox.close(true);
The value true, tells the close() method to call expunge() method. Note that POP3 does not support expunge() method. So, close() method should be called with an argument true for POP3.
The following is a program that deletes all the messages from the folder “inbox”.
import java.util.Properties; import javax.mail.*; public class DeleteEmail {
public static void main(String[] args) throws Exception {
String host = “pop.gmail.com”, protocol = “imaps”;
String username = “usr.some”, password = “some.usr”;
Properties props = new Properties();
Session session = Session.getlnstance(props);
//session.setDebug(true);
Store store = session.getStore(protocol);
store.connect(host, username, password);
Folder inbox = store.getFolder(“Inbox”);
if (inbox.exists()) {
inbox.open(Foldev.READ_WRITE);
Message[] emails = inbox.getMessages();
for (int i = 0; i < emails.length; i++){
System.out.pvintln(”Deleting Message ” + (i + 1));
emails[i].setFlag(Flags.Flag.DELETED,tvue);
}
inbox.close(tvue);
}
else
System.out.pvintln(”Inbox not available”); stove.close();
}
}
Since, this program is potentially dangerous as it deletes all the messages from a folder, make sure you either have copies of these messages stored elsewhere or the folder does not contain any important messages. A sample output is shown in Figure 15.10:
2. REPLYING TO MAILS
To reply to an email received (and retrieved using POP or IMAP), repiy() method may be used.
Message reply(boolean replyToAll)
This method returns a new Message suitable for reply. This means reply() configures headers and attributes of the reply Message properly. For example, the sender becomes the recipient, subject is set to the original subject prefixed with “Re: ” etc. However, the content of this new Message will be empty. The Boolean parameter indicates whether to reply to only the sender (false) or reply to all (t rue). The following example demonstrates how to reply to an email:
Message replyMsg = recvMsg.reply(false);
replyMsg.setFrom(new InternetAddress(”usr.some@gmail.com”));
replyMsg.setText(”Received your mail.”);
Transport.send(replyMsg);
Make sure that the session properties required to send an email are set properly.
3. FORWARDING MAILS
Unlike reply(), there is no method to get a message suitable for forwarding. So, forwarding an email is a little complicated. A message to be forwarded has two parts: one that contains the old message and a new part which is added during forwarding. This tells us that a forwarding mail is a multipart message. To create a forwarding email, the following steps are required:
- Create a fresh Message which will have two parts
- Set headers and attributes properly
- Create two BodyPart objects
- Fill one BodyPart by new content
- Fill the other BodyPart by old content
- Create a Multipart object
- Add those BodyParts to the Muitpart object
- Finally, set this Multipart object as the content of the message
The following creates a fresh message:
MimeMessage frdMsg = new MimeMessage(session);
Now, set some important headers as follows:
frdMsg.setSubject(”Fwd: ” + message.getSubject());
frdMsg.setFrom(InternetAddress.toString(message.getFrom()));
frdMsg.addRecipients(Message.RecipientType.TO,”usr.some@gmail.com”);
The message is forwarded to an email address: usr.some@gmail.com. Create a Multipart object that will be set as content to the message:
Multipart multipart = new MimeMultipart();
Create a BodyPart object and populate it with text content:
BodyPart newPart = new MimeBodyPart();
newPart.setText(”New Message:\n\n”);
Now, create another BodyPart object to hold the entire content of the original message:
BodyPart oldPart = new MimeBodyPart();
oldPart.setContent(message.getContent(), message.getContentType());
Add these two parts to the Multipart object:
multipart.addBodyPart(newPart);
multipart.addBodyPart(oldPart);
Finally, add this Multipart object to the forwarding message:
frdMsg.setContent(multipart);
This message is now ready for forwarding and can be sent using the following code:
Transport.send(frdMsg);
3. COPYING EMAILS
Messages are copied from one folder to another using copyMessages() method of Folder class:
public void copyMessages(Message[] msgs, Folder dest)
This method, if invoked on a folder, copies specified messages to the specified folder. Note that the specified messages must belong to the source folder. For example, to copy all the messages from inbox folder to backup folder, the following code may be used:
inbox.open(Folder.READ_ONLY);
Message[] emails = inbox.getMessages();
inbox.copyMessages(emails, backup);
Note that the source folder must be opened to get messages from it. However, the destination folder does not have to be opened explicitly. The copyMessages() method invokes the appendMessages() method on the destination folder to append the specified messages.
Also note that the destination folder must exist. If it does not exist, it may be created using the following piece of code:
Folder defaultFolder = store.getDefaultFolder();
Folder backup = defaultFolder.getFolder(”backup”);
backup.create(Folder.HOLDS_MESSAGES);
This creates a folder backup under the root directory. The following program (copyEmaii.java) creates a folder backup and copies all the messages from inbox to this folder.
import java.util.Properties;
import javax.mail.*;
public class CopyEmail {
public static void main(String[] args) throws Exception {
String host = “pop.gmail.com”, username = “usr.some”, password = “some.usr”;
Properties props = new Properties();
Session session = Session.getInstance(props); session.setDebug(true);
Store store = session.getStore(“imaps”);
store.connect(host, username, password);
Folder inbox = store.getFolder(“Inbox”);
Folder defaultFolder = store.getDefaultFolder();
Folder backup = defaultFolder.getFolder(“backup”);
boolean isCreated = backup.create(Folder.HOLDS_MESSAGES);
System.out.println(“created: ” + isCreated);
inbox.open(Folder.READ_ONLY);
Message[] emails = inbox.getMessages();
inbox.copyMessages(emails, backup);
}
}
Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.