We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

Scheduled job for email cleanup

Rashmi11
Tera Contributor

I want to create a scheduled job to delete all undelivered emails for today. Tried doing this with below script but its not working:

var emailGr = new GlideRecord('sys_email');
emailGr.addEncodedQuery('sys_created_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday()^sys_idISNOTEMPTY^subject=Undelivered Mail Returned to Sender');
emailGr.query();
var count = emailGr.getRowCount();
while(emailGr.next()){
var grReport = emailGr.sys_id.getRefRecord();
if(grReport.isValidRecord())
grReport.deleteRecord();
}

1 ACCEPTED SOLUTION

Not applicable

Hi @Rashmi ,

Something like below should work. Elevate your privileges and execute below script from background.

var gr=new GlideRecord('sys_email');

gr.addQuery('type','send-ready');

gr.deleteMultiple();

 

You can also change the type to send-ignored rather than deleting those.

Mark my answer correct & Helpful, if Applicable.

Thanks,

Sandeep

View solution in original post

6 REPLIES 6

Mark Roethof
Tera Patron

Hi there,

Have you considered using a Scheduled Flow instead? Zero code involved.

If my answer helped you in any way, please then mark it as helpful.

Kind regards,
Mark
2020-2022 ServiceNow Community MVP
2020-2022 ServiceNow Developer MVP

---

LinkedIn
Community article, blog, video list

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Mark Roethof
Tera Patron

You could also consider using the Auto Flush table [sys_auto_flush].

If my answer helped you in any way, please then mark it as helpful.

Kind regards,
Mark
2020-2022 ServiceNow Community MVP
2020-2022 ServiceNow Developer MVP

---

LinkedIn
Community article, blog, video list

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Auto flush cannot be used for extensions and sys_email is extension under table rotations

Not applicable

Hi @Rashmi ,

Something like below should work. Elevate your privileges and execute below script from background.

var gr=new GlideRecord('sys_email');

gr.addQuery('type','send-ready');

gr.deleteMultiple();

 

You can also change the type to send-ignored rather than deleting those.

Mark my answer correct & Helpful, if Applicable.

Thanks,

Sandeep