I am new to the salesforce. I am working on the Apex batch jobto get Users info which is class User and stored into the csv/text file. I want username and user emailid stored of All users and this information to the csv/text format. I am new to the salesforce please suggest me where should I start.

As of now I been to the developers console and starting with new class, what next steps I should follow.,

public class UserInformation implements Database.Batchable<SObject>, Schedulable {
    public void execute(SchedulableContext sc) {
        // Do initial setup

        Database.executeBatch(this, query);

    public Database.QueryLocator start(Database.BatchableContext bc) {
         String query = 'SELECT Username,Email from USER';
        return Database.getQueryLocator(query);

    public void execute(Database.BatchableContext bc) {
        // process

    public void finish(Database.BatchableContext bc) {

  • Your requirement is to write a batch job OR to get the details of the Users? If just to get details of the users, you can simply take these from the Reports tab. Else if Batch job, query all the User record and create an Attachment of contentType text/csv and set the body of the Attachment as your formatted string that you can construct from the query result. – Vignex Nov 25 '14 at 8:38
  • @Vignex I have to create a batch job, can you help me in query also, shall i give query say "select * from User;" in query editor, something like this? and how to create the attachments – user3226440 Nov 25 '14 at 8:46
  • You need to select the required fields/columns in the query. SF doesn't allow Select * from Table. Your query should be "SELECT Username,Email from USER". For Attachment you can go through the SF documentation: salesforce.com/developer/docs/api/Content/… – Vignex Nov 25 '14 at 8:51
  • @Vignex please can you give idea, where should i start, I am still confuse and exploring , do I need to create a Apex class and write query like in url oyecode.com/2011/10/how-to-use-batch-apex-in-salesforce.html or something else – user3226440 Nov 26 '14 at 12:29
  • Yes. You need create an apex class as mentioned by the link provided by you. – Vignex Nov 26 '14 at 12:32

You can try the following code.

public class UserInformation implements Database.Batchable<SObject>, Database.Stateful {
    string[] Lines;     ///  all records

    public Database.QueryLocator start(Database.BatchableContext bc) {
        lines = new String[0];
        String query = 'SELECT Username,Email from USER';
        return Database.getQueryLocator(query);

    public void execute (Database.BatchableContext bc, SObject[] scope) {
        // process
        for(Sobject record: scope) {
            String line = '';
            // header row
            if ( lines.size() == 0 ) {
                line = 'UserName, Email';
            else {
                // build your csv line here
                line +='"'+ record.get('UserName')  +'"'
                +',' +'"' + record.get('Email') + '"';               

                system.debug('Line No >>> ' + line); 
        }  // end of for loop

    public void finish(Database.BatchableContext bc) {
        // this will send the CSV file as an attachment
        String finalResults = String.join(lines, '\n');
        lines = null; // Free temp memory to avoid heap errors

        //Create a new File Attachment, Message (email) object, attach the distinct
        //list of Record Type names and send via email
        Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
        blob csvBlob = Blob.valueOf(finalResults );
        string csvname= 'filename.csv';
        Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
        String[] toAddresses = new string[] {'[youremail@yourdomain.com]'};
        String subject ='abc';
        email.setToAddresses( toAddresses );
        email.setPlainTextBody('RecordType CSV');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});


  1. http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm

P.S Why do you want to have execute(SchedulableContext sc)? It is used for scheduling. You might not need this. In case you do, I suggest you read this.

To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable.

  • Thanks for this, I went to developer console and created a Apex class, pasted the same code, saved and trying to run from Test> new Run> but my class name is not displaying in list of classes.. how do I test it – user3226440 Nov 27 '14 at 7:05
  • An easier way to test this is to - Create a class, copy code from above and paste. - goto developer console > Debug > Execute anonymous and paste this code - database.executebatch(new UserInformation (),500); - Press "Execute" button at the bottom to run the batch class. Make sure that you only run the line shown above. – Mahmood Nov 27 '14 at 7:09
  • @user3226440: I have updated the code, sorry I didnt initially tested it. But it is now working fine. Plz try it, just updated the interface implementation and initialization of lines[] array. – Mahmood Nov 27 '14 at 7:33
  • Hi sorry for silly question, I m new to salesforce, how do i debug the code and check logs atleast. from Eclipse, I right click on apex class--> force.com--> run test but I am not getting any output or logs, even in the Debug Logs in salesforce page , no logs is there – user3226440 Nov 27 '14 at 8:22
  • It is simple, if you want to debug some piece of code-block, you need to place "System.debug('check me: ' + var/obj name);" and then goto Setup>Monitoring>Debug logs, search your user and add to the monitored user list. Run the code, batch class or test functionality from VF/Controller and Viola! Debug logs will now have messages wherever you put system.debug in your code. Plz read this for a detailed understanding. salesforce.com/us/developer/docs/apexcode/Content/… – Mahmood Nov 27 '14 at 8:34

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.