In ongoing integration project we had to add e-mail notification (by Zawinski's law). For development, we are using well known Apache James Server. Setting it up was piece of cake but for initial testing it is good to test send and receive functionality. That can be done in numerous ways, one is to use Groovy. Because we use Java to send e-mail, using Groovy for testing, makes perfectly sense.
To send e-mail one can make use of ant task for sending mail from Groovy. Script is straight forward and inspired by this ONJava article. There is one caveat though, one must load javax.mail library via systemClassLoader.
Putting it all together it looks like self explanatory script below:
To read e-mail, Groovy can also be handy, but script is not one-liner as one above. It is actually rewrite of some Java class found on internet. Use both scripts as you like.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@GrabConfig(systemClassLoader=true) | |
@Grapes( | |
@Grab(group='javax.mail', module='mail', version='1.4.4') | |
) | |
def ant = new AntBuilder() | |
ant.mail(mailhost:'localhost', mailport:25, subject:'Test message') { | |
from(address:'mySystem@localhost') | |
cc(address:'mySystem@localhost') | |
to(address:'tester@localhost') | |
message("Test mail sent on ${new Date()}") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.mail.*; | |
import javax.mail.internet.*; | |
@GrabConfig(systemClassLoader=true) | |
@Grapes( | |
@Grab(group='javax.mail', module='mail', version='1.4.4') | |
) | |
// setup connection | |
Properties props = new Properties(); | |
def host = "localhost"; | |
def username = "testuser"; | |
def password = "password"; | |
def provider = "pop3"; | |
// Connect to the POP3 server | |
Session session = Session.getDefaultInstance props, null | |
Store store = session.getStore provider | |
store.connect host, username, password | |
// Open the folder | |
Folder inbox = store.getFolder 'INBOX' | |
if (!inbox) { | |
println 'No INBOX' | |
System.exit 1 | |
} | |
inbox.open(Folder.READ_ONLY) | |
// Get the messages from the server | |
Message[] messages = inbox.getMessages() | |
messages.eachWithIndex { m, i -> | |
println "------------ Message ${i+1} ------------" | |
m.writeTo(System.out) | |
} | |
// Close the connection | |
// but don't remove the messages from the server | |
inbox.close false | |
store.close() |