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

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

Related

Capture HTML Form Responses in Google Sheets and send a Confirmation Email to the Form Submitter

I want the script to send the created html email template email.html to the person who last submitted the form.
Below is the success message I get in the console:
Below is the actual email that is received by the person who submits the form:
The email.html is formatted correctly and appears perfectly when sent manually.
I hope this is reprex enough.
EDIT: Maybe it's easier if I include the code
function sendEmail () {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var data = ss.getRange(lr,3);
var email = data.getValue();
var message = HtmlService.createTemplateFromFile('email');
var subject = "Test Subject"
GmailApp.sendEmail(email,subject, message);
}
It's not clear why you are using HtmlService.createTemplateFromFile, but from the image it's clear there at least one error, the script misses two methods:
HtmlService.HtmlTemplate.evaluate() to evaluate the Templated HTML
HtmlService.HtmlOutput.getContent() to get the HTML from the HtmlService.HtmlOutput object returned by the previous method.
Another option that looks to be an error is the use of GmailApp.sendEmail(string,string,string) method, as the third parameter should be a string to be used as the email plain text content. If you want to pass HTML, instead use GmailApp.sendEmail(string,string,string, Object)
Related
Emailing Google Sheet range (with or without formatting) as a HTML table in a Gmail message
Sending an email in HTML and plain with a Gmail Apps Script
Google script inject html into html email
References
https://developers.google.com/apps-script/guides/html
https://developers.google.com/apps-script/guides/html/templates
https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String)

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/

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

Send mails from Notes - when it is not used for mail

Ok, in these times when some people move from Lotus Notes to Office 365 I have come across a certain requirement...
An older workflow application sends mail to users. This has worked fine for ages. But now we have a new type of users. These users are just using Notes for a couple of old legacy applications like the one in question.
The error we get is:
File does not exist
And the code that generates it is pretty simple:
Dim session As New NotesSession
Dim db As NotesDatabase
Dim rtitem As NotesRichtextItem
Dim doc2 As NotesDocument
Set db = session.CurrentDatabase
Set doc2 = New NotesDocument(db)
doc2.Form = "Memo"
doc2.Subject = "Test mail " & now
Set rtitem = New NotesRichTextItem (doc2, "Body" )
Call rtitem.AppendText("A simple test....")
Call rtitem.addnewline(2)
Call rtitem.AppendText("Link to complaint ")
Call doc2.Replaceitemvalue("sendto", "john#dalsgaard-data.dk")
doc2.Send( False )
It fails when running the last line....
So, the question really is: How can I code around the this issue?
I know there is no mail file for the user - and I would really prefer not to have to create one for the new users.
Thanks in advance!
/John
Error will appear when user triggering the code doesn't have a mail file specified in person document/location. One option would be to change code to save the new mail directly to server mail.box (assuming server is configured to route mails) or just send the email directly through SMTP using java.
Ok, I have done some trial & error testing on this....
Conclusion so far is that it works in this situation:
In the LOCAL location document (in names.nsf on the computer) you specify:
Mail server - as a server the user can reach
Mail "On Server"
An existing mail file - it can be ANY existing file on the server, it doesn't have to be a mail database.
Actually, a non-conclusive test indicates the mail database even doesn't have to exist (but the user with the setup for testing had to leave - so I couldn't confirm this tonight...)
Edit:
Further testing indicates that this may not be a problem if the user is NOT roaming. I need some further verification that this is actually the reason why I got it working (for one thing you cannot remove the mail file name again once added)... But thought I would add it here.

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)