Skip to content

Email

Purpose

Send emails.

Methods

Binding name: p6.email


Method: Parser readMailbox( Map<String, Object> conf )

Read a mailbox

  • onEmail: closure to parse the email (first argument). Return false to stop mailbox parsing. (cf parse method to see the returned type) [required]
  • type: the mailbox type pop3, imap or imaps (default to imaps)
  • search: Search criteria used to filter emails. (default to flag:!seen)
  • server: server connection configuration (as a Map)
    • mailbox.server.host: host name
    • mailbox.server.username: username
    • mailbox.server.password: password
    • mailbox.server.port: port (default to -1 as disabled value)
    • mailbox.server.folder: folder (default to INBOX)
  • session: session connection configuration (as a Map) depending on mailbox type
  • debug: display debug information such as connection parameters (boolean, default to false)

Parameters have default values based on the mailbox type:

For Session:

  • pop3
    • mail.pop3.host = pop.gmail.com
    • mail.pop3.port = 995
    • mail.pop3.ssl.enable = true
  • imap
    • mail.imap.host = imap.gmail.com
    • mail.imap.port = 143
    • mail.imap.ssl.enable = false
  • imaps
    • mail.imaps.host = imap.gmail.com
    • mail.imaps.port = 993
    • mail.imap.ssl.enable = true

For Server:

  • pop3
    • host = pop.gmail.com
  • imap
    • host = imap.gmail.com
  • imaps
    • host = imap.gmail.com

Note

Server variables from pipeline should be prefixed by mail.server.

The configuration entries used to connect to the server are used with the priority order:

  1. conf value
  2. pipeline value
  3. default value

Note

All the server or session properties passed to the method that are not part of the recognized one will be added to the final parameters

Search:

Recognized search criteria are:

  • subject for the email subject
  • body for the email body
  • from for the email sender
  • flag for the email flags
    • Allowed flags are seen, flagged, answered, deleted, draft, recent and user
    • Multiple flags can be used joining on a ,
    • You can set the negation of the flag by adding a ! before the name

Note

If the search is can’t be expressed with the current mechanism, you can pass instead of a map a SearchTerm. (cf examples)


Method: Parser parse( MimeMessage message )

Parses the given MimeMessage returning a Parser object with the methods:

  • Date getSentDate(): return the sent date
  • Date getReceivedDate(): return the received date
  • String getFirst(List<Address>): return the first address as string
  • List<Address> getTo(): return the list of recipient of type TO
  • String getSingleTo(): return the first of recipient of type TO
  • List<Address> getCc(): return the list of recipient of type CC
  • String getSingleCc(): return the first of recipient of type CC
  • List<Address> getBcc(): return the list of recipient of type BCC
  • String getSingleBcc(): return the first of recipient of type BCC
  • String getFrom(): return the sender
  • String getReplyTo(): return the reply-to
  • String getSubject(): return the subject
  • boolean isMultipart(): is the email multipart?
  • boolean hasHtmlContent(): has the email HTML content?
  • String getHtmlContent(): return the HTML content
  • boolean hasPlainContent(): has the email plain content?
  • String getPlainContent(): return the plain content
  • Collection<String> getContentIds(): return content ids
  • boolean hasAttachments(): has the email attachments?
  • List<DataSource> getAttachmentList(): return attachments
  • DataSource findAttachmentByName(String name): return an attachment by name
  • DataSource findAttachmentByCid(String cid): return an attachment by cid
  • boolean saveAttachment(DataSource dataSource, Path target): save the attachment on the target (returns false on failure)
  • boolean saveAttachment(String name, Path target): save the attachment by it name on the target (returns false on failure)

Method: boolean sendEmail( final String from, final String to, final String plainBody )

Send an email using the JavaMail API. It will return whether the email has been correctly sent or not.

Parameters:

  • from: the sender’s email address
  • to: the recipient’s email address
  • plainBody: the email’s body content as plain text

Method: boolean sendHtmlEmail( final String from, final String to, final String htmlBody )

Send an email using the JavaMail API. It will return whether the email has been correctly sent or not.

Parameters:

  • from: the sender’s email address
  • to: the recipient’s email address
  • htmlBody: the email’s body content as html

Method: boolean sendEmail( final String from, final String to, final String plainBody, final Map<String, String> params )

Send an email using the JavaMail API. It will return whether the email has been correctly sent or not.

Parameters:

  • from: the sender’s email address
  • to: the recipient’s email address
  • plainBody: the email’s body content as plain text
  • params: additional parameters

Method: boolean sendHtmlEmail( final String from, final String to, final String htmlBody, final Map<String, String> params )

Send an email using the JavaMail API. It will return whether the email has been correctly sent or not.

Parameters:

  • from: the sender’s email address
  • to: the recipient’s email address
  • htmlBody: the email’s body content as html
  • params: additional parameters

Method: boolean sendEmail( final String from, final String to, final String plainBody, final Map<String, String> params, final List<Map> mapAttachments )

Send an email using the JavaMail API. It will return whether the email has been correctly sent or not.

Parameters:


Method: boolean sendHtmlEmail( final String from, final String to, final String htmlBody, final Map<String, String> params, final List<Map> mapAttachments )

Send an email using the JavaMail API. It will return whether the email has been correctly sent or not.

Parameters:


Method: boolean sendEmail( final String from, final String to, final String plainBody, final String htmlBody, final Map<String, String> params, final List<Map> mapAttachments )

Send a multipart email containing a plain text and html body using the JavaMail API. It will return whether the email has been correctly sent or not.

Parameters:

  • from: the sender’s email address
  • to: the recipient’s email address
  • plainBody: the email’s body content as plain text
  • htmlBody: the email’s body content as html text
  • params: additional parameters
  • mapAttachments: attachments files

Attachments files

Zero or more attachments can be specified. Unless using the fileurl header the attachment content must be specified as bytes.

Key Description Value
name Used to identify the email body (required) body
type MIME Types (required)
filename Name for attachment
filenurl The URL of a file to attach

Additional parameters of the request

You can set the information below in the params map.

Key Description
profile.name Email profile name to use for the request
profile.appkey Email profile appKey to use for the request
replyto Reply to address
cc Courtesy copy address
bcc Blind courtesy copy address
subject The email subject

Method: boolean sendEmail(String to, byte[] mimeMessageBytes, Map<String, String> mimeHeaders) throws P6Exception

Send an email with the JavaMail API using a RAW MIME encoded header map and body. It will return whether the email has been correctly sent or not.

Parameters:

  • to: the recipient’s email address
  • mimeMessageBytes: the body of the MIME message as a byte array
  • mimeHeaders: a Map of MIME headers to use in the email

Method: boolean sendEmail(String to, byte[] mimeMessageBytes, Map<String, String> mimeHeaders, Map<String, String> params) throws P6Exception

Send an email with the JavaMail API using a RAW MIME encoded header map and body. It will return whether the email has been correctly sent or not.

Parameters:

  • to: the recipient’s email address
  • mimeMessageBytes: the body of the MIME message as a byte array
  • mimeHeaders: a Map of MIME headers to use in the email
  • params: additional parameters

Examples

Above all, you must check that you have a default email profile set in the Email Profiles service.

Example 1

Send the message Hello from dev.b2box.com@amalto.com to toto@amalto.com.

p6.email.sendEmail('dev.b2box.com@amalto.com', 'toto@amalto.com', 'This is email body content.')

Example 2

Same as the first example with an email’s subject.

def params = [ 'subject': 'Email Service Test' ]

p6.email.sendEmail('dev.b2box.com@amalto.com', 'toto@amalto.com', 'This is email body content.', params)

Example 3

Same as the second example with two additional attachments: the hello.txt file and the logo.tiff logo.

def attachments = [
    [
        headers: [
            filename: 'hello.txt',
            type: 'text/plain'
        ],
        bytes: 'This is attachment content'.getBytes()
    ],
    [ 
        headers: [ fileurl: 'file:///opt/p6core.data/logo.tiff' ] 
    ]
]

def params = [ 'subject': 'Email Service Test' ]

print p6.email.sendEmail('dev.b2box.com@amalto.com', 'roxane.mace@amalto.com', 'This is email body content.\n', params, attachments)

Example 4

Send a multipart email

def params = [ ]
def attachments = [ ]

p6.email.sendEmail('dev.b2box.com@amalto.com', 'toto@amalto.com', 'This is plain text email body content.', 'This is <b>html email</b> body content.', params, attachments)

Example 5

Read Gmail mailbox

def config = [
    server: [username: 'user@server.com', password: "secret"],
    onEmail: (email) -> {
       p6.log.debug "Subject: " + email.getSubject()
       p6.log.debug "From: " + email.getFrom()
       p6.log.debug "To: " + email.getSingleTo()
       p6.log.debug "Reply-To: " + email.getReplyTo()
       p6.log.debug "Sent date: " + email.getSentDate()
       p6.log.debug "Received date: " + email.getReceivedDate()
       p6.log.debug "Plain content? " + (email.hasPlainContent() ? "Yes" : "No")
       p6.log.debug "Html content? " + (email.hasHtmlContent() ? "Yes" : "No")
       p6.log.debug "Attachments? " + (email.hasAttachments() ? ("Yes (" + (email.getAttachmentList().size()) + ")") : "No")
       if (email.hasAttachments()) {
           email.getAttachmentList().each { attachment ->
               p6.log.debug " - " + attachment.getName() + " (" + attachment.getContentType() + ")"
               def targetFile = File.createTempFile("email", "attachement");
               log.debug "Saving to... " + targetFile.toString()
               log.debug email.saveAttachment(attachment, targetFile.toPath()) ? "OK" : "Failure";
           }
       }
   }
]

p6.email.readMailbox(config)

Example 6

Read random mailbox

def config = [
    server: [
        username: "username@server.com", 
        password: "password",
        host: "imaps.server.com",
        folder: "Global",
        port: "145",
    ],
    onEmail: (email) -> {
       // Stop on first email without attachment
       return email.hasAttachments();
   }
]

p6.email.readMailbox(config)

Example 7

Search parameters

def config = [
    search: [from: 'sender@server.com', flag: '!seen'],
    server: [
        username: "username@server.com", 
        password: "password",
    ],
    onEmail: (email) -> {
        // Unseen emails from sender@server.com
   }
]
p6.email.readMailbox(config)

Multiple flags

def config = [
    search: [flag: '!seen,draft'],
    server: [
        username: "username@server.com", 
        password: "password",
    ],
    onEmail: (email) -> {
        // Unseen drafts
   }
]
p6.email.readMailbox(config)

Complex search

import javax.mail.search.*;
def config = [
    search: new OrTerm(new FlagTerm(new Flags(Flags.Flag.ANSWERED), true), new FlagTerm(new Flags(Flags.Flag.RECENT), true)),
    server: [
        username: "username@server.com", 
        password: "password",
    ],
    onEmail: (email) -> {
        // answered emails OR recent one
   }
]
p6.email.readMailbox(config)

Example 8

Additional mailbox parameters

p6.pipeline.put('mail.server.token', 'secret')
def config = [
    server: [
        username: "username@server.com", 
        password: "password",
        fee: "foo",
    ],
    session: [
        bar: "bee",
    ],
    debug: true,
    onEmail: (email) -> {
   }
]
p6.email.readMailbox(config)

Will output

Connection parameters form 'imaps'
- Server parameters: ["host": "imap.gmail.com", "username": "username@server.com", "password": "password", "folder": "INBOX", "fee": "foo", "token": "secret"] 
- Session parameters: ["mail.store.protocol": "imaps", "mail.imaps.host": "imap.gmail.com", "mail.imaps.port": "993", "mail.imap.ssl.enable": "true", "bar": "fee"]