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

Views: 531   

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

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("", mailProperties.getHostName())
        props.put("mail.smtp.port", mailProperties.getPort())
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                    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.setContent(bodyText, "text/html")
            log.debug("Sending Email from:{}, to:{}, subject:{}, body:{}", from, toList, subtext, bodyText)
        } 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>()
        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;


private MailProperties mailProperties = // build mail properties

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