Эта статья морально устарела :( . Приглашаю продолжить ваше знакомство с Salesforce на нашем Форуме!
Представим ситуацию, что у вас есть задание уведомить администратора о том, что на вашем сайте зарегистрировался новый человек.
Есть как минимум 2 способа реализации этой ситуации:
- через создание WorkFlow на это событие (добавился новый User) и добавить к нему соответствующий Email Alert
- написать (before insert trigger), который будет вызывать ваш метод для отправки почты (статический метод можно положить в отдельный класс)
Примечание:
WorkFlow - это некоторое бизнес правило, в результате выполнения которого мы можем совершать какие то свои действия. которые повесим на данное соблытие
(Пример: при создании нового пользователя на сайте будем уведомлять администратора об этом)
Разберем первый способ:
Для того. что бы создать наш WorkFlow нам необходимо перейти в этот раздел:
setup / create / Workflow & Approvals / Workflow Rules
setup / create / Workflow & Approvals / Workflow Rules / имя вашего Workflow
Customize / User / Trigger
trigger CachNewSiteUserRegister on User (after insert) {
for(User user : Trigger.new){
SentNotificationForAdmin.SendNoteForAdmin(user.id, user.Name, user.Email);
}
}
public class SentNotificationForAdmin {
public static void SendNoteForAdmin(Id user_id, String user_name, String user_email){
// First, reserve email capacity for the current Apex transaction to ensure
// that we won't exceed our daily email limits when sending email after
// the current transaction is committed.
Messaging.reserveSingleEmailCapacity(2);
// Processes and actions involved in the Apex transaction occur next,
// which conclude with sending a single email.
// Now create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'roman.bazylev.vrp@gmail.com'};
String[] ccAddresses = new String[] {'support@bikeshop-developer-edition.ap1.force.com'};
// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);
// Specify the address used when the recipients reply to the email.
mail.setReplyTo('roman.bazylev.vrp@gmail.com');
// Specify the name used as the display name.
mail.setSenderDisplayName('BikeShop Support');
// Specify the subject line for your email address.
mail.setSubject('New User was registered : ' + case.Id);
// Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);
// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);
// Specify the text content of the email.
mail.setPlainTextBody('New User was registered: ' + user_id + ' name: ' + user_name + ' Email: ' + user_email + '');
mail.setHtmlBody('New User was registered: ' + user_id + ' name: ' + user_name + ' Email: ' + user_email + '');
// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
public static void getTemplateBody (){
EmailTemplate et;
Id templateId = '00X90000000k0VJ';
et = [SELECT id, Name, Subject, Body, TemplateType, Markup, HtmlValue FROM EmailTemplate WHERE id = :templateId];
if (et.TemplateType == 'visualforce'){
String template = et.Markup;
template = template.replace('{0}','Our data');
system.debug('seeeeee:'+ template);
}
}
String template = et.Body;
//SiteReisterController.cls
//...
String userId = Site.createPortalUser(u, accountId, password);
if (userId != NULL) {
User newPortalUser = [SELECT Name, Email FROM User WHERE Id=:userId];
//...
//something todo