Dynamic recipient list in the Email Ext Jenkins plugin - email

I am using the Email Ext Jenkins plugin and it was working quite well.
Now I need to set the recipients list dynamically. Basically for each build I get a list of email recipients in a file and I need to use that list. My question is:
Is there a way to set an Environment Variable so that that can be modified and Recipient List will get that consume that environment variable.
I know there is a solution to set programmatically recipients of Jenkins Email-ext plugin in the pre-send script.How To set programmatically recipients of jenkins email ext plugin. However for my case there are some difficulty with that solution as I need to read a file which contains a list of Emails.

If the format of the file is either comma separated or space separated, you could just use the FILE token (see the content token reference in the plugin). That should put the contents of the file into the recipients list.

I can't test this right now so I can't remember if apache commons is available.
Create a file called recipients.groovy with the following contents:
<%
def stream = new FilePath(build.workspace, "yourfile.txt").read();
def recipients = IOUtils.toString(stream, "UTF-8");
%>
${recipients}
And in your jobs configuration, in the recipients list, you put ${SCRIPT, script="recipients.groovy"}
API References:
FilePath
AbstractBuild
Referring to the recipients.groovy in the Recipient List, gives the following exception:
Failed to create e-mail address for Error in script or template: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script1.groovy: 1:
unexpected token: < # line 1, column 1. <% ^ 1 error
Full Exception below:
groovy.lang.MissingPropertyException: No such property: build for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
at Script1.run(Script1.groovy:4)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:150)
at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:122)
at hudson.remoting.LocalChannel.call(LocalChannel.java:45)
at hudson.util.RemotingDiagnostics.executeGroovy(RemotingDiagnostics.java:119)
at jenkins.model.Jenkins._doScript(Jenkins.java:3400)
at jenkins.model.Jenkins.doScript(Jenkins.java:3377)
at sun.reflect.GeneratedMethodAccessor344.invoke(Unknown Source)

You can use the Inject environment variables plugin (https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin) and to create a var during run time, or the Propagate build environment variables (https://wiki.jenkins-ci.org/display/JENKINS/Build+Env+Propagator+Plugin) to change an existing one, and then you can use this var in the Project recipient list when you are using Editable Email Notification (https://wiki.jenkins-ci.org/display/JENKINS/Email-ext+plugin)

Related

Odoo14: Send an email through code using a recordset in the template

Using a scheduled task, I need to send an email which will inform on the status of open tasks. After getting the recordset correponding to my search, I found how to load the template and send the email:
mail_template = self.env.ref('test_email.email_template')
mail_template.send_mail(self.id)
But I only got access to the current record in $object. I would like to be able to pass the recordset to the template and loop over it.
You can use the context to "transport" data into the mail rendering:
mail_template.with_context(my_recordset=my_recordset).send_mail(self.id)
In your mail template just use ctx:
%for record in ctx.get('my_recordset', []):
<div>${record.my_attribute}</div>
%endfor

Sending Emails in Nestjs

I am trying to send email in NestJs but seems to stuck at a weird error.
TypeError: Cannot destructure property 'templateName' of 'precompile(...)' as it is undefined.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:363:5)
at ServerResponse.setHeader (node:_http_outgoing:573:11)
I am not sure what's going on the only solution I was able to find was to put ''./'' in front of the template names but I am not sure why would that work also it isn't even working in my case.
This is how i am trying to send it
this.mailService.sendEmail(
emailAddress,
[], // cc
[], // bcc
"Pretty Subject Line", // subject
"./verify-email", // template
{ // context
name: "tetsName",
verifyLink
}
);
templates folder is in root directory
Cannot set header error mostly occurs when you are sending a response after once you have sent a response. Take a look at the following code
//This does not work
res.send("This is a Response");
res.send("This is a second response");
If you are doing something like this, then it won't work. Try a logic that does all the tasks you want in one go or use may
res.write("This is a response"):
res.end();
For me,this is a template file path issue. Review your template.dir in your MailerModule config, and compare it to your project "dist" directory. if your template file path is "dist/templates/template.hbs" then your template.dir should be ${process.cwd()}/templates else if your dist directory is "dist/src/templates/template.hbs" ,which is depend on your compile configs. then your template.dir config should be join(__dirname, 'templates')

Jenkins dynamically set $DEFAULT_CONTENT

I need to execute a script (groovy) and use the content generated by the script for sending an email. The body of the email is the content. I am not sure how to do this as $DEFAULT_CONTENT is mentioned to be a token (enabled by token plugin). Can some one help me on how to achieve this. I am using the execute groovy script and Email-ext plugin. Thanks and appreciate any help.
According to the documentation of Email-ext+plugin
https://wiki.jenkins.io/display/JENKINS/Email-ext+plugin
$DEFAULT_CONTENT should be a variable filled from the Default Content field from the global configuration page
I haven't used Email-Ext in plain groovy, but in pipeline I use it like the following:
emailext attachLog: true, compressLog: true, recipientProviders: [culprits()],
subject: "Issue on branch ${env.BRANCH_NAME}",
body: """<p>Job ${env.JOB_NAME} #${env.BUILD_NUMBER} failed</p>
<p>Result of my Script ${MY_SCRIPT_RESULT}</p>
<p>Check console output at <a href='${env.BUILD_URL}'>${env.JOB_NAME} #${env.BUILD_NUMBER}</a></p>"""
Here ${MY_SCRIPT_RESULT} would be the value of variable MY_SCRIPT_RESULT.
MY_SCRIPT_RESULT could be a variable I exported to variable environment for instance

Send an email when a boolean is true

I am trying to send an email whenever a boolean value equals. The email needs to contain info from a list that is created in a groovy script earlier in the job. whenever this list isn't empty I will need to create a text/HTML email with the contents of the list.
currently I have the email extension plugin but I can't find a way to integrate it with what I need. Is there anyway I could send the email using groovy or use a plugin that triggers based on what I need?
To anyone who it may concern, I discovered that with the Flexible Publish Plug in you can add conditionals to your post build actions, easiest to use string values and just compare those. this is because you can set up parameters at the start of your build that you plan to use to store info in the build environment, and it can be accessed from other places.
you can set string params using the following code:
def paramTempHolder = new StringParameterValue('PARAM', 'desired value')
build.replaceAction(new ParametersAction(paramTempHolder))
for me I used send to indcate I needed to send my email so my code read:
def paramTempHolder = new StringParameterValue('SendEmail', 'send')
I then used $SendMail as string 1 in flexible publish and just send as string 2. If the condition is meet it will send my email. I can use the same parameter manipulation to get the info I need into my email so that it sends like I want it to.
EDIT: I forgot to mention that inorder to use the replaceAction method you will need to add the following import to your script:
import hudson.model.*

Jenkins email-ext plugin thinks I have no recipients configured

I'm using Jenkins 2.2 and email-ext plugin 2.42 (both current, as are all of the rest of my plugins). I have my global configuration set to have a single, explicit recipient and my project is using default email notification configuration (that is, send to $DEFAULT_RECIPIENTS). I have also set an explicit recipient in the project. In both configurations, the console output for the job says:
An attempt to send an e-mail to empty list of recipients, ignored.
This would seem to be https://issues.jenkins-ci.org/browse/JENKINS-13583 except
1. that was marked as resolved four years ago, and 2. I get e-mail when I use basic, built-in notifications. Does anyone else see this problem with email-ext?
Turns out plugin configuration is somewhat non-intuitive; a necessary setting is buried behind an Advanced button. I got answers in https://issues.jenkins-ci.org/browse/JENKINS-34731 and it is working now as follows:
In the Advanced settings, Triggers -> Failure - Any lists "Developers" by default, but not "Recipient List."
For those using this plugin in combination with Job DSL. I have do add the sendTo { recipientList() } block explicitly to the different triggers.
So my DSL looked like this:
extendedEmail {
recipientList('${EMAIL_RECIPIENTS}')
triggers {
failure {
subject('The subject')
content("The content")
sendTo {
recipientList()
}
}
}
}
Instead of using $DEFAULT_RECIPIENTS use to:
emailext(
to: 'somename#emailprovider.com',
body: '${DEFAULT_CONTENT}',
mimeType: 'text/html',
subject: '${DEFAULT_SUBJECT}',
replyTo: '$DEFAULT_REPLYTO'
)
}
Ref: https://stackoverflow.com/a/39499554/1134084
I finally found the problem through repeated attempts. There is no need for such trouble at all. The reason is that in the advanced Settings of Editable Email Notification trigger condition, the Recipient List is empty by default, and all your Settings outside will be overridden. An attempt to send an e-mail to empty list of recipients was ignored. An attempt to send an E-mail to empty list of recipients ignored.