Exchange Web Services (EWS) Java API for O365
Accessing Mailbox we need an Exchange Web Services Java API, You can download a jar from below link.
Creating a service
To access the EWS service, We need to create an instance for ExchangeService class.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2)
Manually setting the URL,
service.setUrl(new URI('https://outlook.office365.com/EWS/exchange.asmx'))
Web Credentials
ExchangeCredentials credentials = new WebCredentials(Username, Password)
service.setCredentials(credentials)
Email Message Schema
It represents email properties such as From, Sender, ToRecipients, CcRecipients, Attachments, ReplyTo, IsRead, MimeContent, etc..
import microsoft.exchange.webservices.data.core.service.schema.EmailMessageSchema
Search Filter
The search filter is used to search for a specific property set. The search filter is a base class. There is a different type of search filters available few features are given below:
- IsEqualTo
- IsGreaterThan
- IsLessThan
- ContainsSubstring
You have a scenario where only a new email has to read after a given time. The below code is used to read email after that duration.
import microsoft.exchange.webservices.data.search.filter.SearchFilter
import java.text.SimpleDateFormatSimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
readerTime = 1572414743000 // Epoch Timedef lastTime = formatter.format(new Date(readerTime.toLong()))
Date startDate = formatter.parse(lastTime)SearchFilter isGreaterThan = new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, startDate);
Item View
Item view represents the view settings in a folder search operation, Itemview constructor has a single parameter and its data type is Int32. It is used for the page size. The below code provides the first 100 emails from the Inbox.
import microsoft.exchange.webservices.data.search.ItemViewItemView itemview = new ItemView(100);
Find Items Results
It will return <TItem> as per the search operation.
import microsoft.exchange.webservices.data.search.FindItemsResultsFindItemsResults findResults = service.findItems(WellKnownFolderName.Inbox, new SearchFilter.SearchFilterCollection(LogicalOperator.And, isGreaterThan ), itemview);// Number emails are found
println "No. of records: "+findResults.getTotalCount()
ExchangeService.LoadPropertiesForItems
We can load multiple items to the load property. It has to use after FindItemsResults.
service.loadPropertiesForItems(findResults, new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.Attachments, EmailMessageSchema.MimeContent));
Items
Represents a generic item. Properties available on item are defined in the ItemSchema class.
for (Item itemtest : findResults){
println "Subject: "+itemtest.getSubject()
println "Email Size: "+ itemtest.getSize()
println "Sender: "+ itemtest.getSender().getName()
println "Reply Address: "+ itemtest.getInReplyTo()
println "Date of Sent: "+ itemtest.getDateTimeSent()
println "Date of Received: "+ itemtest.getDateTimeReceived()
println "Is New: "+ itemtest.getIsNew()
println "Mail Importance: "+itemtest.getImportance()
println "Mail Content: "+itemtest.body
itemtest.load(itempropertyset);
}
Write an email message to eml file
MimeContent mailContent = itemtest.getMimeContent();byte[] mailcontent = mailContent.getContent(); // No stream option?
if( mailcontent.length > 0)
{
// Write content to message.eml
String itemFileName = + Calendar.instance.time.time + ".eml";
itemFileName = itemFileName.replaceAll("[/<>+^:,]","");
FileOutputStream fileStream = new FileOutputStream(itemFileName);
fileStream.write(mailcontent);
fileStream.close();
}
Attachment
Using getHasAttachments(), we will come to know the email have at least a single attachment.
Majorly there are two types of attachments:
- Item attachments
- File attachments
Item attachments contain Email message, Calender item, Task, Contact group, and a hierarchy of item attachments. File attachments contains a .txt, .jpg, .zip, .pdf, or even a .msg files.
if (itemtest.getHasAttachments()) {
AttachmentCollection attachmentsCol = itemtest.getAttachments()
if(attachmentsCol.getCount() > 0)
{
long first14 = Calendar.instance.time.time
def filePathStr = "/rootpath/"
def folder = new File(filePathStr+first14)
if(!folder.exists())
{
folder.mkdir()
}
for (int i = 0; i < attachmentsCol.getCount(); i++) {
if((attachmentsCol.getPropertyAtIndex(i) instanceof ItemAttachment))
{
try {
ItemAttachment itemAttachment = (ItemAttachment) ((attachmentsCol.getPropertyAtIndex(i) instanceof ItemAttachment) ? attachmentsCol.getPropertyAtIndex(i) : null)itemAttachment.load(new PropertySet(ItemSchema.MimeContent)); // No file option?
Item item = itemAttachment.getItem();
if (item instanceof EmailMessage)
{
MimeContent mimeContent = item.getMimeContent();
byte[] content = mimeContent.getContent(); // No stream option?
if( content.length > 0)
{
// Write content to message.eml
String itemFileName = itemAttachment.getName() + ".eml";
itemFileName = itemFileName.replaceAll("[/<>+^:,]","");
itemFileName = filePathStr+itemFileNameoemailAttachment.fileNameAttach = itemFileName
oemailView.addToEmailAttachment(oemailAttachment)
FileOutputStream fileStream = new FileOutputStream(rootPath+itemFileName);
fileStream.write(content);
fileStream.close();
}
}
println "Item Attachement able to read"
}
catch(Exception e) {
println e
}
}
else{
FileAttachment attachment = (FileAttachment)attachmentsCol.getPropertyAtIndex(i);
String attachFileName = attachment.getName()
attachFileName = attachFileName.replaceAll("[/<>+^:,]","_")
attachFileName = filePathStr + attachFileName
attachment.load(attachFileName)
}
}
}
}
Mark email as read
//set mail as read
itemtest.isRead = true;
itemtest.update(ConflictResolutionMode.AutoResolve);
I hope you found this helpful!