Is it possible to send emails from the Jenkins Script Console?

后端 未结 2 1585
醉梦人生
醉梦人生 2021-02-11 04:27

To automate user registration in a new Jenkins instance, I have generated a Groovy script:

// Automatically generated groovy script -- 1463047124
j         


        
相关标签:
2条回答
  • 2021-02-11 04:58

    You could try utilize Java-like code withing your Groovy script:

    import javax.mail.*
    import javax.mail.internet.*
    
    
    def sendMail(host, sender, receivers, subject, text) {
        Properties props = System.getProperties()
        props.put("mail.smtp.host", host)
        Session session = Session.getDefaultInstance(props, null)
    
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(sender))
        receivers.split(',').each {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(it))
        }
        message.setSubject(subject)
        message.setText(text)
    
        println 'Sending mail to ' + receivers + '.'
        Transport.send(message)
        println 'Mail sent.'
    }
    

    Usage Example:

    sendMail('mailhost', messageSender, messageReceivers, messageSubject, messageAllText)
    
    0 讨论(0)
  • 2021-02-11 04:59

    This script is superb!! works very well.... But I amended it to:

    i) call jenkins environment variables to send Build Status in my email subject.

    ii) send Email Body with multiple lines as per my requirement like below - Hope it helps!! (added below section in addition to the script mentioned above)

    def result = manager.build.result
    manager.listener.logger.println "And the result is: ${result}"
    def environment = manager.getEnvVars()
    def body = "Job Name: ${environment.JOB_NAME} "+ 
    System.getProperty("line.separator")+" Build Number: 
    
    ${environment.BUILD_NUMBER} "+ System.getProperty("line.separator")+" Build 
    Status: ${result} " + System.getProperty("line.separator") 
        + " DEPLOYMENT INFORMATION: Check Deployment Console Output at ${environment.BUILD_URL} "
        + System.getProperty("line.separator")
        + " Disclaimer: Please do not reply to this email as this is an auto-generated email from Jenkins"
    
    def subject = " ${environment.JOB_NAME}>> ${environment.BUILD_NUMBER} >> ${result} "
    sendMail('hostxyz@com', "jenkins@com", "abc@com", "APPID>>${subject}", "${body}")
    
    0 讨论(0)
提交回复
热议问题