+ Start a Discussion

Not Able to send MassMail from Apex Class.



I'm developing apex class to send mass emails from selected records, when i select records and click on send button it show runtime error.


I'm getting this error message


System.NullPointerException: Attempt to de-reference a null object

Class.wrapperClassController3.send: line 128, column 22 External entry point


Wat may be the problem? Please help me to rectify this.


Apex Class code:

public class wrapperClassController3 {
public String aMessage {
get; set;
public List<ID> studentids;
public List<string> studentList1=new List<string>();
//public String[] studentList1 = new List<String>();
//Our collection of the class/wrapper objects cStudent
public List<cStudent> studentList {get; set;}

//This method uses a simple SOQL query to return a List of Students
public List<cStudent> getStudents(){
if(studentList == null){
studentList = new List<cStudent>();

for(Student__c c : [select Id, First_Name__c,Last_Name__c, Email__c from Student__c limit 10]){

studentList.add(new cStudent(c));
return studentList;

public PageReference processSelected(){
/*We create a new list of Student that we be populated only with Students
if they are selected*/
List<Student__c> selectedStudents = new List<Student__c>();
this.aMessage = '';
/*We will cycle through our list of cStudents and will check to see if the
selected property is set to true, if it is we add the Contact to the
selectedStudentss list. */
for(cStudent cCon : getStudents()){
if(cCon.selected == true){

/* Now we have our list of selected contacts and can perform any type of
logic we want, sending emails, updating a field on the Contact, etc */
System.debug('These are the selected Students...');
Integer numselectedStudents = selectedStudents.size();
Integer counter = 0;
for(Student__c con : selectedStudents){

if(counter==numselectedStudents) {
this.aMessage += con.Id + ','+ con.First_Name__c+',' + con.Email__c;
} else {
this.aMessage += con.Id + ','+con.First_Name__c+','+ con.Email__c+', ';

return null;


/* This is our wrapper/container class. A container class is a class, a data
structure, or an abstract data type whose instances are collections of other
objects. In this example a wrapper class contains both the standard salesforce
object Contact and a Boolean value */
public class cStudent
public Student__c con {get; set;}
public Boolean selected {get; set;}

/*This is the contructor method. When we create a new cContact object we pass a
Contact that is set to the con property. We also set the selected value to false*/
public cStudent(Student__c c){
con = c;
selected = false;


// public class mail
// public String subject { get; set; }

// public String body{ get; set; }

public PageReference send()

Messaging.MassEmailMessage email = new Messaging.MassEmailMessage();
// String[] toAddresses = new String[] {};
List<String> TargetObjectIds = new List<String>();
//for(String s:studentList1)
// String[] toAddresses = new String[] {s};
// TargetObjectIds.add(s);
// ID s;

for(ID s:studentids)
email.setSubject( 'subject' );

//String[] toMassTargetObjects = new String[]{toMassTargetObjects};
//email.setPlainTextBody( body );
email.setSenderDisplayName('Customer Support');
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.MassEmailMessage[] {email});
PageReference Page = new PageReference('/mailinfo');
return Page;
// return null;
catch(Exception e)
return null;






Visualforce Code.



<apex:page controller="wrapperClassController3">
<apex:outputPanel id="selected"><b>Selected: {!aMessage}</b></apex:outputPanel>
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton value="Process Selected" action="{!processSelected}" rerender="selected"/>
<apex:commandButton value="Send" action="{!send}"/>
<!-- In our table we are displaying the cStudent records -->
<apex:pageBlockTable value="{!students}" var="c" id="table">
<apex:column >
<!-- This is our selected Boolean property in our wrapper class -->
<apex:inputCheckbox value="{!c.selected}"/>
<!-- This is how we access the student values within our cStudent container/wrapper -->
<apex:column value="{!c.con.First_Name__c}" />
<apex:column value="{!c.con.Last_Name__c}" />
<apex:column value="{!c.con.Email__c}" />







Thank you.



Message Edited by Coder on 12-19-2009 03:24 AM
Message Edited by Coder on 12-20-2009 08:17 PM
Message Edited by Coder on 12-20-2009 08:22 PM

This post is a few years old, so I don't know if it's been resolved yet. But it seems to me that you have two problems:


#1: you're only adding the last student IDs from the list of selected students. In your else loop you need to include the "studentList1.add(con.Id);" as well


 if(counter==numselectedStudents) {
this.aMessage += con.Id + ','+ con.First_Name__c+',' + con.Email__c;
} else {
this.aMessage += con.Id + ','+con.First_Name__c+','+ con.Email__c+', ';


#2: after you get this list of ids, you're not using it to send your email. 


for(ID s:studentids)

you're trying to set your target ids from a null list that you declare and then never fill. Change the for loop to cycle through the studentList1 that you stored your IDs in



Hope that helps


Hi woodmanzee,


Am trying to implement something similar to the above & i have made the necessary changes that you adviced i.e adding

studentList1.add(con.Id); in the else part as well as changing the for loop to cycle through the studentList1.


for(ID s:studentList1)


The error is no longer there,however,the processSelected() method seems to work ok,but send() method doesn't seem to work. Could this be because the TargetObjectIds is set to Custom object id's ?


It's possible... I couldn't get it to work with the mass email message and so I made a temporary fix with Single Email Messages. Here's what I came up with, and it works, but it sends out the emails one at a time, which could be a problem with a large address listing.


    public PageReference send() {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[recipientList1.size()];
        Integer index = 0;
        for (String s : recipientList1) {
            toAddresses[index] = s;

        try {
            Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            PageReference goodPage = new PageReference('/apex/mailinfo');
            PageReference badPage = new PageReference('/apex/mailinfobad');
            if (this.body == '' || toAddresses.size() == 0) {
                return badPage;
            }else {
                return goodPage;
        } catch(Exception e) {
            return null;



It works fine for now, but if you get the MassEmail working let me know


Hi Woodmanzee,


Am trying using the SingleEmailMessage but the 'toaddresses'n doesn't seem to work since am getting this error from my Debug Log

05:13:05.184 (184476000)|EXCEPTION_THROWN|[112]|System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc): []

Below is my send() method code:


public PageReference send() {
         eTemplate = [Select id,Body,Subject,DeveloperName from EmailTemplate where DeveloperName = 'Interview_Client_Email' ];
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[candidateList1.size()];
        Integer index = 0;
        for (String s : candidateList1) {
            toAddresses[index] = s;
        try {
            Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            PageReference goodPage = new PageReference('/apex/mailinfo');
            PageReference badPage = new PageReference('/apex/mailinfobad');
            if (eTemplate.body == '' || toAddresses.size() == 0) {
                return badPage;
            }else {
                return goodPage;
        } catch(Exception e) {
            return null;