Snippets

Matthew Clark Send Email Method example - Can be used in any script where it makes sense to use it

Created by Matthew Clark last modified

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.mail.Email
import com.atlassian.mail.MailException
import com.atlassian.mail.server.SMTPMailServer
import com.atlassian.jira.mail.settings.MailSettings
import org.apache.log4j.Logger
import org.apache.log4j.Level

def log = Logger.getLogger(getClass())
log.setLevel(Level.DEBUG)


String sendEmail(String emailAddr, String subject, String body) {

    def log = Logger.getLogger(getClass())
    log.setLevel(Level.DEBUG)

    // Stop emails being sent if the outgoing mail server gets disabled (useful if you start a script sending emails and need to stop it)
    MailSettings mailSettings = ComponentAccessor.getComponent(MailSettings)
    if ( ! mailSettings?.send()?.disabled) {

        SMTPMailServer mailServer = ComponentAccessor.getMailServerManager().getDefaultSMTPMailServer()

        String result

        if (mailServer) {
            Email email = new Email(emailAddr)
            email.setMimeType("text/html")
            email.setSubject(subject)
            email.setBody(body)
            try {
                mailServer.send(email)
                log.debug("Mail sent")
                return result = "Success"
            } catch (MailException e) {
                log.debug("Send mail failed with error:" + e)
                return result = "Failed to Send Mail, Check Logs for error"
            }
        } else {
            log.debug("Your mail server Object is Null, make sure to set the SMTP Mail Server Settings Correctly on your Server")
            return result = "Failed to Send Mail. No SMTP Mail Server Defined"
        }

    } else {
        return "Your outgoing mail server has been disabled"
    }
}

Comments (0)