2016-05-12 61 views
2

要在新詹金斯例如自動用戶註冊,我已經產生了Groovy腳本:是否可以從Jenkins腳本控制檯發送電子郵件?

// Automatically generated groovy script -- 1463047124 
jenkins.model.Jenkins.instance.securityRealm.createAccount("username", "NGRkOGJiNGE2NDEyMTExMDI0OGZmOWNj") 
def user = hudson.model.User.get("username"); 
def userEmail = "[email protected]"; 
user.addProperty(new hudson.tasks.Mailer.UserProperty(userEmail)); 

然後我可以粘貼到詹金斯腳本控制檯或詹金斯CLI運行它,它會創建用戶。

我想添加到此設置的下一件事是通過電子郵件通知新用戶他們的帳戶已創建的能力。我懷疑這可以完成,因爲「郵件程序」安裝在我的Jenkins實例中。例如,使用時尚管道,如代碼,我可以添加到我的Jenkinsfile:

它將發送。但是,這不能在CLI或腳本控制檯中重現。這甚至有可能嗎?

回答

3

你可以嘗試使用類似Java的代碼withing你的Groovy腳本:

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.' 
} 

用法示例:

sendMail('mailhost', messageSender, messageReceivers, messageSubject, messageAllText) 
+0

嗯我試過了,但它什麼也沒做。我不認爲哈德森/詹金斯直接使用'javax.mail' .. –

+0

'mailhost'是否指有效的郵件服務器? – luka5z

+0

是的,我在jenkins配置中使用。雖然很難調試groovy腳本:_( –

0

這個腳本是一流的!作品非常好.... 但我修改爲:

i)調用jenkins環境變量在我的電子郵件主題中發送構建狀態。

ii)根據我的要求發送電子郵件正文有多行,如下所示 - 希望它有幫助! (除了上面提到的腳本之外,在下面添加的部分)

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('[email protected]', "[email protected]", "[email protected]", "APPID>>${subject}", "${body}")