SMTP ( Simple Mail Transfer Protocol ) wrapper to send emails in Groovy

Views: 194   

Java's javax.mail.* package helps you send emails with SMTP protocol. Following is a groovy code wrapper helps you simplify the SMTP email sending.

import groovy.util.logging.Slf4j

import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

@Slf4j
public class Mailer {

    static void send(
            MailProperties mailProperties,
            String from,
            List<String> toList,
            String subtext,
            String bodyText) {

        Properties props = new Properties()
        props.put("mail.smtp.auth", "true")
        props.put("mail.smtp.host", mailProperties.getHostName())
        props.put("mail.smtp.port", mailProperties.getPort())
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(mailProperties.getUserName(), mailProperties.getPassWord())
                    }
                })
        try {
            Message message = new MimeMessage(session)
            message.setFrom(new InternetAddress(from))
            for (String toEmail : toList) {
                message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail))
            }
            message.setSubject(subtext)
            message.setContent(bodyText, "text/html")
            log.debug("Sending Email from:{}, to:{}, subject:{}, body:{}", from, toList, subtext, bodyText)
            Transport.send(message)
        } catch (MessagingException e) {
            log.error("Exception while sending mail " + e.getMessage())
        }
    }

    static void send( MailProperties mailProperties,String from, String to, String subtext, String bodyText) {
        List<String> toList = new ArrayList<String>()
        toList.add(to)
        send(mailProperties,from, toList, subtext, bodyText)
    }
}
public class MailProperties {

    private final String userName;
    private final String passWord;
    private final String hostName;
    private final String port;
}

Usage

private MailProperties mailProperties = // build mail properties

 Mailer.send(mailProperties,"[email protected]", "[email protected]",
                "subjeccte tes", "body tes");
On By