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())

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

    def log = Logger.getLogger(getClass())

    // 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)
            try {
                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)