Splunk Search

Sendemail (Splunk CLI) always sends email whether results are available or not...

the_wolverine
Champion

I'm running the following search from Splunk CLI:

./splunk search 'index=test | search _raw!="scoobydoo" | sendemail to="elvis@splunk.com,john@splunk.com" subject=myresults server=mail.splunk.com' -auth etc:pass

The behavior I see is that an email is always sent whether or not results are returned by the search.

Is there some way to tell Splunk to only send email when there are results?

Tags (2)

woodcock
Esteemed Legend

Do it like this:

... | rename COMMENT1of3 AS "Splunk sendemail ALWAYS sends email, even when no results found; we address this with 2 settings:"
| rename COMMENT2of3 AS "First, we put 'null()' in 'to' header when no results; this causes 'sendemail' to error."
| rename COMMENT3of3 AS "Last, we use 'graceful=true' so that the search does not log any error for that."
| eval valueForToHeader=if(isnotnull(someFieldNameInYourResults), "YourGoodEmailGoesHere@YourCompany.com", null())
| sendemail
   to=$result.valueForToHeader$
   graceful=true
   ...
0 Karma

gkanapathy
Splunk Employee
Splunk Employee

You could consider running using the Splunk scheduler, and using Splunk's conditional script triggering rather than running the search at the CLI.

0 Karma

Stephen_Sorkin
Splunk Employee
Splunk Employee

No, Splunk doesn't provide per-result set branching logic in the search language.

I would script this using the Python SDK:

import time
import splunk
import splunk.auth   as au
import splunk.search as se

splunk.mergeHostPath('localhost:4001', True)
key = au.getSessionKey('admin', 'changeme')

d = se.dispatch('search index=_internal | head 10')

while not d.isDone:
    time.sleep(1)

if d.resultCount > 0:
    d.setFetchOption(search='sendemail to=...@splunk.com from=...@splunk.com server=ip1.splunk.com subject=myresults sendresults=true')
    r = d.results[0]

You can then run this via: splunk cmd python <scriptname>.py

A shell script may be even easier.

Get Updates on the Splunk Community!

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...

Introducing the 2024 Splunk MVPs!

We are excited to announce the 2024 cohort of the Splunk MVP program. Splunk MVPs are passionate members of ...

Splunk Custom Visualizations App End of Life

The Splunk Custom Visualizations apps End of Life for SimpleXML will reach end of support on Dec 21, 2024, ...