如何在Groovy & Grails项目中使用Java将Outlook收件箱选中的邮件保存至本地磁盘?
Hey there! I’ve worked on integrating Outlook with Groovy/Grails projects before, so here’s a practical approach to save selected emails from your Outlook inbox to local disk:
The key here is leveraging Microsoft Outlook's COM Interop (since Groovy seamlessly works with Java/COM components). We'll use the JACOB library to bridge Groovy and Outlook's COM API, allowing us to access the active Outlook instance, retrieve selected emails, and save them in MSG format (or other formats like HTML/TXT if needed).
First, add the JACOB dependency to your Grails project's build.gradle:
implementation 'net.sf.jacob-project:jacob:1.19'
(Note: Make sure the JACOB version matches your Outlook's 32/64-bit architecture—download the correct DLL from the JACOB project and place it in your JRE's bin folder if needed.)
Here’s a reusable Groovy function to handle the save operation:
import com.jacob.activeX.ActiveXComponent import com.jacob.com.Dispatch import com.jacob.com.Variant def saveSelectedOutlookEmails(String targetDirectory) { // Connect to the running Outlook instance (or launch it if not running) def outlookApp = new ActiveXComponent("Outlook.Application") def activeExplorer = outlookApp.getProperty("ActiveExplorer").toDispatch() def selectedItems = Dispatch.get(activeExplorer, "Selection").toDispatch() def itemCount = Dispatch.get(selectedItems, "Count").getInt() if (itemCount == 0) { println "No emails selected in Outlook. Please select at least one email first!" outlookApp.safeRelease() return } // Create target directory if it doesn't exist def saveDir = new File(targetDirectory) if (!saveDir.exists()) { saveDir.mkdirs() println "Created directory: ${saveDir.absolutePath}" } // Iterate over selected emails and save each for (int i = 1; i <= itemCount; i++) { def mailItem = Dispatch.call(selectedItems, "Item", new Variant(i)).toDispatch() def emailSubject = Dispatch.get(mailItem, "Subject").toString() // Clean up invalid characters from the filename def safeFilename = emailSubject.replaceAll("[\\\\/:*?\"<>|]", "_") + ".msg" def fullSavePath = new File(saveDir, safeFilename).absolutePath // Save the email as MSG file (3 = olMSG format) Dispatch.call(mailItem, "SaveAs", fullSavePath, new Variant(3)) println "Successfully saved: ${safeFilename}" } // Release COM resources to avoid memory leaks outlookApp.safeRelease() } // Example usage: Save selected emails to C:\Outlook_Saved_Emails saveSelectedOutlookEmails("C:/Outlook_Saved_Emails")
- Outlook Security Prompt: Outlook may show a security warning when accessing emails via external apps. To bypass this, you can either:
- Adjust Outlook's Trust Center settings (enable programmatic access for trusted apps), or
- Use an Outlook VBA macro to trigger the save operation (since macros have higher trust levels), then call the macro from Groovy if needed.
- Thread Safety: If you're building a web-based Grails app, avoid running this code directly in a request thread—Outlook is a desktop app, so this logic should run in a background task (like using Quartz) or be part of a desktop-facing tool.
- Alternative Formats: Change the second parameter in
SaveAsto save in other formats:0= Plain Text (.txt)4= HTML (.html)5= MIME (.eml)
内容的提问来源于stack exchange,提问作者Ram

