+ Start a Discussion
Ritika JRitika J 

Creating Users through Apex



How can i send generate password email when i am creating new users through apex.




Anu Raj.ax1269Anu Raj.ax1269

Hi Ritika,

 I don't know what are you exactly looking for. I have tried to solve your problem please look into the code. I have used 2 password field because Auto generate field cannot be edited so as password should be changed by the user as he like, so i have get password into another field also.



The password__c is Auto Number (date type). eg: A-{000}



trigger email on Password_generate__c (after insert) {

list<Password_generate__c > pglst = new list<Password_generate__c >();
set<id> pgId = new set<id>();
map<id, Password_generate__c > mapPg = new map<id, Password_generate__c >();

for(Password_generate__c pg: trigger.new){

if(pg.UserName__c != null ){

system.debug('password__c >>>>>>>> ' + pg.password__c);
// pg.UserPassword__c = pg.password__c;
mapPg.put(pg.id, pg);
system.debug('UserPassword__c >>>>>>>> ' + pg.UserPassword__c );



pglst = [select password__c, UserPassword__c, UserName__c from Password_generate__c where id = :pgId];

for(integer i =0; i<pglst.size(); i++){

pglst[0].UserPassword__c = mapPg.get(pglst[0].id).password__c;

String[] toaddress = new String[]{pglst[0].UserName__c};
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setsubject('Your Password ');
mail.setPlainTextBody ('Use this password -- '+ pglst[0].UserPassword__c);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

update pglst;





Ritika JRitika J

Hey thanks for your reply.

I just want standard email notification (password notification mail )should go to user when i am inserting it through apex.


Take a look at the DMLOptions: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database_dmloptions.htm#emailheader

Database.DMLOptions opts = new Database.DMLOptions();
opts.EmailHeader.triggerUserEmail = true;
User u = new User();
// set various fields on u, etc.
insert u;