function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dr. Thomas MillerDr. Thomas Miller 

Delete tasks related to EMailMessages

If I create an EMailMessage record via SOAP API, the SF system automatically creates an associated task record which is shown in the activity history or open activities related list.
Now, if I did something wrong and delete the EMailMessage record (as I cannot update it) the task record is left.
It can be deleted from the related list UI but doesn't show up in a SOQL query nor in a Data Loader export.
Is there any programmatic way to get rid of these task records?
Alain CabonAlain Cabon
Hi,

These tasks have the subtype "Email" and the field ACTIVITYID has the ID of the task in EMAILMESSAGE.

Apex/SOQL : SELECT count(id) FROM Task WHERE tasksubtype = 'Email'  ( and ISARCHIVED = true and ISDELETED = true ALL ROWS )

Apex: DELETE [ SELECT ID FROM EMAILMESSAGE WHERE ACTIVITYID = '00T0Y00000DtrdmUAB' ];

The deletion of the Emailmessage delete also the associated task ( ACTIVITYID is filled in Emailmessage ).

Other tests: 

https://help.salesforce.com/articleView?id=000199524&type=1

https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_guidelines_archive.htm

What is the result when you search via the "Mass Delete" (setup : Data Management > Mass Delete Records > Activities​ )
with the criteria "Activity Subtype" equals "Email" ?

User-added image

User-added image
Best regards

Alain
Dr. Thomas MillerDr. Thomas Miller
Thanks for the hints. In fact the true problem as that the migrated messages were old and the system had them set to archived. I was able to get rid of them using a batch database job with a query similar to yours.