So here's the scenario. You want to send an email that uses template for the email subject and body to a customer email address. You will probably need to set the Template Id but Salesforce also requires you to set the Target Object Id as well. The Target Object Id could be the Record Id of Contact, Lead, or User.

Say, you don't have the related Contact or Lead Id for this email, you still could use the current user Id by UserInfo.getUserId() or use the record owner Id for the Target Object Id.

But...but, your email address is now displayed along with the customer email address as the recipient which is not good because you probably don't want your email address to be exposed to customer.


In short, here is the solution to send email with templates to customer without associating any target object:


    // initialize temporary email list
    List<Messaging.SingleEmailMessage> messageList = new List<Messaging.SingleEmailMessage>();
    
    // initialize one or more single emails as you need 
    Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
    Messaging.EmailFileAttachment efa = new Messaging.EmailfileAttachment();

    // set the sender email
    message.setOrgWideEmailAddressId([SELECT Id FROM OrgWideEmailAddress WHERE Address = 'do_not_reply@example.com' LIMIT 1].Id);
    
    // set the recipient email
    message.setToAddresses(new String[] { 'test@test.com' });

    // set the email template id
    message.setTemplateId( [SELECT Id from EmailTemplate where developername='The_Name_of_the_Email_Template_That_You_Use'].Id);     
    
    // do not save email as activity
    message.setSaveAsActivity(false);

    // set the id for the object
    message.setWhatId([SELECT Id FROM Custom_Object__c LIMIT 1].Id);

    // set target object id as your current user id
    message.setTargetObjectId( UserInfo.getUserId() );

    // add current message to message list
    messageList.add(message);

    // create savepoint before executing statement
    Savepoint sp = Database.setSavepoint();

    // send the temporary email list
    Messaging.sendEmail(messageList);

    // rollback the transaction before commiting to database
    Database.rollback(sp);

    // initialize the actual message list to be sent
    List<Messaging.SingleEmailMessage> actualMessageList = new List<Messaging.SingleEmailMessage>();
    
    // loop through the previous message list and set the email fields
    for (Messaging.SingleEmailMessage email : messageList) {
        Messaging.SingleEmailMessage emailToSend = new Messaging.SingleEmailMessage();
        emailToSend.setToAddresses(email.getToAddresses());
        emailToSend.setHTMLBody(email.getHTMLBody());
        emailToSend.setSubject(email.getSubject());
        emailToSend.setOrgWideEmailAddressId(email.getOrgWideEmailAddressId());
        emailToSend.setFileAttachments(email.getFileAttachments());
        actualMessageList.add(emailToSend);
    }

    // send the actual message list
    Messaging.SendEmailResult [] serList = Messaging.sendEmail(actualMessageList);

    // make sure the emails are sent successfully
    String errorMessage = '';
    for(Messaging.SendEmailResult ser : serList){
        if(!ser.isSuccess()){
            for(Messaging.SendEmailError err : ser.getErrors()) {
                errorMessage += err.getMessage() + '\n';
            }
        }
    }

There you have it! Hope it helps! See ya!

Post was published on , last updated on .

Like the content? Support the author by paypal.me!