Introduction
In this small tip, I will explain how we can save emails with attachment in Outlook's draft folder using Java programming language.
Using the Code
I am using Eclipse to write this small application, following are the packages we need for this application:
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
In the main function, you can specify MailFrom
, SMTP
host and MailTo
in the following variables:
String to = "emailto@yourcompany.com";
String from = "emailfrom@yourcompany.com";
String host = "yourcompanyhoust.com";
Next, we need to create Mail properites, e.g., SMTP
host and store in session
variable:
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
After that, following is a simple self-explanatory code to create new email message, add the message subject, load the attachment from local drive and attach it with email:
Message message = new MimeMessage(session);
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "C:/temp/bb.log";
FileDataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Next, we need to add IMAP
host properties and specify the IMAP
host along port 993:
properties.setProperty("mail.store.protocol", "imaps");
properties.setProperty("mail.imaps.port", "993");
session = Session.getDefaultInstance(properties, null);
javax.mail.Store store = session.getStore("imaps");
store.connect("outlook.your_org.com", "XXXXX", "XXXXXX");
Once we are able to connect to store
, we can easily browse through all Outlook folders, e.g., Inbox, Sent Items, Drafts, etc. In the following code, we are accessing the Drafts folder, opening it with Read & Write access and finally appending the above created message.
Folder draft = store.getFolder("drafts");
draft.open(Folder.READ_WRITE);
draft.appendMessages(new Message[] { message });
System.out.println(
draft.getFullName()
+ " has : "
+ draft.getMessageCount()
+ " Message(s)");
After executing the above application, you should see a new message in your Outlook draft folder.
History