I am working on a scenario in which on creating a contact than a user from apex code. I am not able to send a welcome email with the URL of setting new password. here is my code:

    public Static void CreateContact_User(String conFirstName, String conLastName, String conEmail, String accId, String deprtmnt, String mobileNo, String city, String emailEnkey, String timeZnKey, String localSKey, String langLocalKey, String CompName ){
        Contact contactRecord       = new Contact();
        contactRecord.FirstName     = conFirstName;
        contactRecord.LastName      = conLastName;
        contactRecord.Email         = conEmail;
        contactRecord.AccountId     = accId;
        contactRecord.Department    = deprtmnt;
        contactRecord.MobilePhone   = mobileNo;
        contactRecord.MailingCity   = city;
        insert contactRecord;

        Profile portalProfile                    = [SELECT Id FROM Profile WHERE Name='Customer Community User' Limit 1];

        Database.DMLOptions DmlO                 = new Database.DMLOptions();
        DmlO.EmailHeader.triggerUserEmail        = true;

        User user1 = new User(UserName = contactRecord.Email, FirstName = contactRecord.FirstName, LastName = contactRecord.LastName, Alias = conLastName,
                              Email= contactRecord.Email, ContactId = contactRecord.ID, ProfileId = portalProfile.Id, EmailEncodingKey = emailEnkey,
                              CommunityNickname = contactRecord.FirstName, TimeZoneSidKey = timeZnKey, LocaleSidKey = localSKey,
                              LanguageLocaleKey = langLocalKey, CompanyName= CompName );
        Insert user1;     

        Database.SaveResult result = Database.update(user1 ,DmlO);
        System.debug('result:- '+result);

        User userId = [Select Id from User where Id=:user1.Id];
        System.debug('Users Id :- '+userId);




enter image description here

Based on the above, you'd replace your insert call with a database call using the information linked and shown above.

Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail = true;

database.insert(user1, dlo);
  • Hi, I tried but it's not working. – Laxmi Oct 30 '19 at 17:28
  • I'd check if you're in a sandbox that email delivery is turned on. Otherwise, I don't think there's any options left if the documentation is incorrect or I'm misreading it. – Kris Goncalves Oct 30 '19 at 17:39

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.