Search code examples
grailsgrails-plugingrails-2.0

Plugin for email fetching in a grails application


I am using grails 2.x. I am looking for a plugin or any reocmmendation. I need to cover functionality to fetch emails from email providers (e.g. gmail, ...). After fetching the mail I look into my database if I know the senders email address. If yes I save the email in my database. If no a skip the message.

So far I only found plugins used for sending out emails but not for fetching emails.

Is there any code (plugin, or pure java code) I could reuse for this request?


Solution

  • There isn't any plugin available but using JavaMail is pretty simple. Here is a quick example of fetching messages from an inbox from a POP3 server:

    import javax.mail.*
    import javax.mail.internet.*
    
    String popHost = "mail.wherever.com"
    String popUsername ="someone@wherever.com"
    String popPassword = "password123"
    
    Properties properties = new Properties()
    
    properties.put("mail.pop3.host", popHost)
    properties.put("mail.pop3.port", "995")
    properties.put("mail.pop3.starttls.enable", "true")
    Session emailSession = Session.getDefaultInstance(properties)
    
    // create the POP3 store object and connect with the pop server
    Store store = emailSession.getStore("pop3s")
    store.connect(popHost, popUsername, popPassword)
    
    // create the folder object and open it
    Folder emailFolder = store.getFolder("INBOX")
    emailFolder.open(Folder.READ_WRITE)
    
    // retrieve the messages from the folder in an array
    Message[] messages = emailFolder.getMessages()
    log.debug("${messages.length} messages found to process")
    
    messages.each { message ->
        log.debug("Processing e-mail message")
        log.debug("Subject: " + message.getSubject())
        log.debug("From: " + message.getFrom()[0])
    }
    

    This is just a simple example, may contain typos and such since I wrote it off the top of my head. Assuming you're using Groovy and inside a Grails Service.

    Note: This example assumes the use of SSL and port of 995. This is true for such providers as gmail, but not all.