0

Is there any way to populate {!Opportunity.link} while sending email through apex? or Is there any way to replace {!Opportunity.id} with 15 or 18 character id like: https://xx.salesforce.com/{!Opportunity.Id}

Below is my code: I am trying replace "{!Opportunity.id} with op.id" in order to add that id to my url https://xx.salesforce.com/ in the template.

EmailTemplate emailTemplates = [Select Body, HtmlValue, Id, Name, Subject from EmailTemplate where Name = ' Email notification on Opportunity' Limit 1];
List<Messaging.SingleEmailMessage> theEmails = new list<Messaging.SingleEmailMessage>();
for (Opportunity op : newList) {

   list<string> emaillist = new list<string>();
   emaillist.add(bccEmail);
   string body = emailTemplates.Body;
   body = body.replace('{!Opportunity.Name} ', op.Name);
   body = body.replace('{!Opportunity.id}', op.id);

   string subject = emailTemplates.Subject;

   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   mail.setToAddresses(emaillist);
   mail.setTemplateId(emailTemplates.Id);
   mail.setSaveAsActivity(false);
   mail.setSubject(subject);
   mail.setPlainTextBody(body);

   theEmails.add(mail);
}
1

You can use this method to get the current base url of your Salesforce instance:

system.url.getsalesforcebaseurl().toexternalform()

So then you can do something like this:

String sfUrl = system.url.getsalesforcebaseurl().toexternalform();
body = body.replace('{!Opportunity.id}',sfUrl+'/'+op.id);
1

Since you're using a template, you can't also set the body. Instead, use setWhatId to associate the email to the opportunity, and this should allow the merge fields to work correctly:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(emaillist);
mail.setTemplateId(emailTemplates.Id);
mail.setSaveAsActivity(false);
mail.setWhatId(op.Id);

Also, if possible, consider using a user ID with setTargetObjectId to minimize the "bulk email" usage limits.

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(UserInfo.getUserId()); // Or another user you get from a query...
mail.setTemplateId(emailTemplates.Id);
mail.setSaveAsActivity(false);
mail.setWhatId(op.Id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.