function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ATUL GUPTA 94ATUL GUPTA 94 

How to create community user using apex code

I am creating community user ,Iam able to create user but Iam not gettting Email  in user mail id .


Lead rec = new Lead();
        rec.LastName ='pooja';
        rec.Phone = '8983443423';
        rec.Email = 'pooja@oaktreecloud.com';
        rec.Country = 'India';
        rec.Company = 'testing';
        rec.Status =    'Open - Not Contacted';
        rec.Password__c = 'test123';
        insert rec;



 Account acc = new Account();
            acc.Name= (rec.FirstName !=null ? rec.FirstName + ' '+ rec.LastName : rec.LastName);

            insert acc;
            
            Contact con = new Contact();
            con.LastName=  rec.LastName;
            con.AccountId = acc.id;
            insert con;
            
            User user = new User();
            user.ProfileID = [Select Id From Profile Where Name='Customer Community User'].id;
            user.EmailEncodingKey = 'ISO-8859-1';
            user.LanguageLocaleKey = 'en_US';
            user.TimeZoneSidKey = 'America/New_York';
            user.LocaleSidKey = 'en_US';
            user.FirstName = (rec.FirstName !=null ? rec.FirstName + ' '+ rec.LastName : rec.LastName);
            user.LastName = rec.LastName;
            user.Username = '12354545'+rec.Email;   
            user.CommunityNickname = rec.LastName;
            user.Alias = 't1';
            user.Email = rec.Email;
            user.IsActive = true;
            user.ContactId = con.Id;
            
ase.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail = true;

 Database.insert(user,dlo);