Send an email when a boolean is true - email

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.*

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

CakePHP 3.x - Email to log instead of sending during debug

I would like to switch my application to a configuration where email isn't actually send, but instead saved to a log file.
This way I can test my application normally without being afraid of accidentally emailing to hundreds of users and without spamming myself.
I figured something with EmailTransports could be a solution. For instance, when using the DebugTransport the emails aren't send at all, the mail content is instead only returned by the ->send() function.
The downside of this transport is than I have to modify controller code in order to display the content, which I would like to avoid.
So is there a configuration such that email is stored to files instead of being sent, e.g.:
[root]
logs/
emails/
2019-10-01_15:32_email#example.com.txt
2019-10-01_16:54_another_recipient#example.com.txt
...
There is no such built-in configuration, no, but you can easily create your own custom transport that logs emails to files instead of sending them.
Here's a very basic example transport that extends the debug transport, and writes the data to a custom logging scope:
namespace App\Mailer\Transport;
use Cake\Log\LogTrait;
use Cake\Mailer\Email;
use Cake\Mailer\Transport\DebugTransport;
use Psr\Log\LogLevel;
class TestTransport extends DebugTransport
{
use LogTrait;
public function send(Email $email)
{
$data = parent::send($email);
$this->log(json_encode($data), LogLevel::DEBUG, ['scope' => ['emails']]);
return $data;
}
}
See also
Cookbook > Email > Using Transports > Creating Custom Transports

Salesforce send Email by Apex

I'm making by a requirement a code able to send an E-mail to an specific list of E-mails, due the fact that I must to include the attachments of the record I decided to use an apex class instead an e-mail alert. This object (A custom object ) must populate some fields in an email template with some of the record´s fields. I implemented the following code
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(lista);
mail.setTemplateId('00X21000000QR22');
//mail.setWhatId(idMinuta);
mail.setTargetObjectId('005d0000005NMIx');
mail.setSaveAsActivity(false);
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
for (ContentVersion document: documents)
{
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(document.Title);
efa.setBody(document.VersionData);
fileAttachments.add(efa);
}
mail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
I understood that to make the fields merge it´s necesary to use the WhatId method. In the related code, I have commented it because It generates an error (INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.)
My question is, if is it possible to do this with a custom object. I´m a little confuse with salesforce documentation beacuse it looks like the method supports a custom object, or maybe If I am forggeting something to include in the code.
If i keep the WhatID line commented, effectively the email is sent with the attachments and the Template but it is not populated.
I really need this kind of solution because the org have in this object at least 20 email templates, for me will be easier just to pass the Id of the template instead of makig a code with 20 different html codes for each situation
Thanks a lot
Please publish this question at Salesforce StackExcahnge https://salesforce.stackexchange.com/

Is there a way to fetch latest email from "Mail reader sampler" or "Beanshell Sampler"

I am able to fetch email from my email account using POP3 via "Mail Reader Sampler" listener. But its not retrieving latest email.
Is it possible to extract the latest email using Beanshell Sampler. If yes, can you please share the code if this is achievable.
As per below discussion - looks like it is not doable. But, wanted to check if this is achievable using any means?
Stackoverflow Discussion on how to fetch required email
You can do this programmatically, check out the following methods:
Folder.getMessageCount() - Get total number of messages in this Folder
Folder.getMessage(int msgnum) - Get the Message object corresponding to the given message number
According to the JavaDoc
Messages are numbered starting at 1 through the total number of message in the folder.
So the number of the last message will always be the same as the total number of messages in the given folder.
Example code which reads last email using POP3 protocol
import javax.mail.Folder
import javax.mail.Message
import javax.mail.Session
import javax.mail.Store
String host = "host"
String user = "username"
String password = "password"
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties)
Store store = session.getStore("pop3")
store.connect(host, user, password)
Folder inbox = store.getFolder("Inbox")
inbox.open(Folder.READ_ONLY)
int msgCount = inbox.getMessageCount()
Message last = inbox.getMessage(msgCount)
//do what you need with the "last" message
inbox.close(true)
store.close()
I would also recommend forgetting about Beanshell, whenever you need to perform scripting - use JSR223 Elements and Groovy language as Groovy has much better performance, it is more Java-compliant and it has some nice language features. See Apache Groovy - Why and How You Should Use It guide for more details.

Dynamic recipient list in the Email Ext Jenkins plugin

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)