+ Start a Discussion
Yogesh BiyaniYogesh Biyani 

How do remove the email message after it is sent

In compliance with GDPR, we have implemented a process to delete all the user information from the database. After deleting the data we send a final email to the requester informing the actions taken. However, the final email message stays in the database and has the email address of the recipient. How can we delete the email after it is sent? 

Here is the code which sends the confirmation email. 
public void SendConfirmationEmailMessage(Contact_Preference__c cp){
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.toAddresses = new String[] { cp.Email__c };
        message.setSubject('Data Deletion Confirmation Email');
        message.setHtmlBody(Messaging.renderStoredEmailTemplate('00X1W000001USk9', null, cp.id).getHTMLBody());
     Messaging.SingleEmailMessage[] messages =  
            new List<Messaging.SingleEmailMessage> {message};

     Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        if (results[0].success) {
            System.debug('The email was sent successfully.');
        } else {
            System.debug('The email failed to send: '
                  + results[0].errors[0].message);


Raj VakatiRaj Vakati
You could able to delete from the EmailMessage Object 
Delete [ Select Id from EmailMessage ]

Yogesh BiyaniYogesh Biyani
Is this something I can do right after the send call? 

Raj VakatiRaj Vakati
yes or use scheduler to delete the emails 
Sandeep Adhikari RSandeep Adhikari R
After email sent successfully, you have the list of contact preferences.Store the ID for success records and query that and delete it.
But I believe you can't delete using this way :
Delete [ Select Id from EmailMessage ]

Please follow the below approach:
1.store the ids of sucessful records in to a set.
if (results[0].success) {
  //store the ids
  System.debug('The email was sent successfully.');
2.After Messaging.SingleEmailMessage completed query those records using the ids that were stored in first step
3.Delete the records.

Yogesh BiyaniYogesh Biyani
@Sandeep, How do I get the message ID and can I delete it right after the sendEmail call? 
Sandeep Adhikari RSandeep Adhikari R
@Yogesh, I believe you are passing the list of records(id,email,other field data) as a parameter (Contact_Preference__c cp)
Yogesh BiyaniYogesh Biyani
Yes, but the messages are not owned by any records.
Sandeep Adhikari RSandeep Adhikari R
You just need the ID to delete the records.Grab the id value form (Contact_Preference__c cp) .

Can you list the field data that you are passing in parameters