Search code examples
jenkinsgroovysmtpjenkins-plugins

What is the best way to escape quotes via Groovy?


How do I fix the url syntax for the below script?

I'm attempting to run this in a Jenkins job and receive the below bold error. I tried adding backspace before quote to escape and even surround double quotes with single quotes. What am i doing wrong?
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 8: expecting anything but ''\n''; got it anyway @ line 8, column 190. " -SmtpServer "smtp.gmail.com"

pipeline {
agent any
stages {
    stage("Using curl example") {
        steps {
            script {
                final String url = "Send-MailMessage -From me@gmail.com -To you@gmail.com -Subject "Send Test Message to Mailout Relay" -Body "Test Message" -SmtpServer "smtp.gmail.com"

                final String response = sh(script: "curl -s $url", returnStdout: true).trim()

                echo response
            }
        }
    }
}

}


Solution

  • You have, at least, 2 options:

    Use single quotes inside the double quotes (replace the final String url line with this one):

    final String url = "Send-MailMessage -From me@gmail.com -To you@gmail.com -Subject 'Send Test Message to Mailout Relay' -Body 'Test Message' -SmtpServer 'smtp.gmail.com'"
    

    or escape the double quotes inside the string:

    final String url = "Send-MailMessage -From me@gmail.com -To you@gmail.com -Subject \"Send Test Message to Mailout Relay\" -Body \"Test Message\" -SmtpServer \"smtp.gmail.com\""