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
ElectronElectron 

Messaging.MassEmailMessage & setTargetObjectId SetWhatId

Hi I am writing an APEX Trigger to send MassEmail, I learned I could use SetTargetObjectId for MassEmailMessage, from this link:

http://www.forcetree.com/2009/07/sending-email-from-your-apex-class.html

 

I want to use setTargetObjectId, this method works very well in SingleEmailSeassage.

When I use it for MassEmailMessage,

 

It keeps showing the error

 

Method does not exist or incorrect signature

 

I thought I may give the wrong value for this method, I tried the List, Set<Id>, etc.

None of them works.

 

Does MassEmailMeassage supports this method, or it only supports it in APEX Class, not trigger?

 

the error came for SetWhatId, too. 

 

Update: 

Thanks Puja,

 

I forget to add things I did try the "setTargetObjectIds" and  "setTargetObjectId", but both of them shows same error for me. 

Best Answer chosen by Admin (Salesforce Developers) 
Puja_mfsiPuja_mfsi

Hi,

yes you can send mail through trigger with MassEmailMessage .

Please use this code 

 

public List<Id> contactIds = new List<Id>();
contactIds.add(Trigger.New[0].Id);

 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(contactIds);
 mail.setTemplateID('00X90000001EWno');
 Messaging.sendEmail(new Messaging.MassEmailMessage[] {mail});   

 

And if still get the error please send me your code snippet then i will check.

 

All Answers

Puja_mfsiPuja_mfsi

Hi,

For massEmailMessage you use the "setTargetObjectIds" not "setTargetObjectId" .

Please take reference from the below link:

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

ElectronElectron

Hi Puja,

Thank you, I did try setTargetObjectIds, but it still shows the same error.

Does it support in a trigger?

Puja_mfsiPuja_mfsi

Hi,

yes you can send mail through trigger with MassEmailMessage .

Please use this code 

 

public List<Id> contactIds = new List<Id>();
contactIds.add(Trigger.New[0].Id);

 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(contactIds);
 mail.setTemplateID('00X90000001EWno');
 Messaging.sendEmail(new Messaging.MassEmailMessage[] {mail});   

 

And if still get the error please send me your code snippet then i will check.

 

This was selected as the best answer
ElectronElectron

Yes, I found that, too the various must be ID.
It should be List<ID> or ID[], I shouldn't use Set<ID>.

ElectronElectron

Hi Puja,

 

Thank you so much. But I am facing another error in my Unit Test.

 

It shows the error

System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing target object ids (contact, lead or user): 

The TargetId is the Contact Owner, it's User ID, right? 

 

I have the code 

targetObjectIds.add(contacts.OwnerId);

But every time I run the test, it shows me the error. 

 

Did you face this situation before.

Puja_mfsiPuja_mfsi

Hi,

Yes this is the user Id.ok you take the reference from Here.

 

Trigger:

public List<Id> contactIds = new List<Id>();
for(Contact con : trigger.New ) {
contactIds.add( con.OwnerId);
}
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
mail.setTargetObjectIds(contactIds);
mail.setTemplateID('00X90000001EWno');
mail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.MassEmailMessage[] {mail});

 

TestClass

Contact con = new Contact(
LastName = 'puja tt'
);
insert con;

 

You need to just create a new record of contact.

If still you gives an error please lete me know

And if this is helpful to you please give me the feedback with click on star at left side.

ElectronElectron

Hi Puja,

 

I feel there is better way to solve the error except post my code, please check below. 

 

I worried that I shouldn't use add the Contact Owner ID directly. 

 

Thank you so much.

 

trigger updateClassOwner on Contact (after update) {

	String mailTemplateId = [SELECT id FROM EmailTemplate WHERE Name = 'updateClassOwner'].id;
	//To get the Id from Trigger
	Set<Id> classIds = new Set<Id>();
	//The Id for sending Email
	List<ID> targetObjectIds = new List<ID>();
	List<ID> whatIds = new List<ID>(); 
	
	for(Contact fellow: trigger.new)
	{
		classIds.add(fellow.Id);
	}
	
	List<Class__c> fellowClass = new List<Class__c>([SELECT id, OwnerID FROM Class__c WHERE fellow__c in: ClassIds]);
	List<Class__c> updateClass = new List<Class__c>();
	
	for(Contact fellow: trigger.new)
	{
		//compare if contact's owner is changed.
		Contact oldOwner = Trigger.oldMap.get(fellow.Id);
		If(oldOwner.OwnerId != fellow.OwnerId)
		{
			targetObjectIds.add(fellow.OwnerId);
			whatIds.add(fellow.Id);
			//query all the class that this fellow is teaching
			for(integer i = 0; i < fellowClass.size(); i++)
			{
				//update Class' OwnerId
				fellowClass[i].OwnerId=fellow.OwnerId;
				updateClass.add(fellowClass[i]);
			}
		}
	}
		
	update updateClass;
	If(targetObjectIds != null)
	{
	    Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
	    mail.SetTargetObjectIds(targetObjectIds);
	    mail.setTemplateId([SELECT id FROM EmailTemplate WHERE Name = 'updateClassOwner'].id);
	    mail.setWhatIds(whatIds);
	    mail.saveAsActivity = false;
	    Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail }); 
	}
}

 

Thank you so much for help. 

Puja_mfsiPuja_mfsi

Hi,

Ok I got the solution .

You need to check the

If( targetObjectIds != null && targetObjectIds.size() > 0  ) {

}

Because of this check if "targetObjectIds" list have no records it will never go to the if block.

You only check the null but if you initialize a list then it never equals to null,that's why it is go to the if bloack and give the exception

ElectronElectron

Hi Puja,

  

Thank you so much, but I have to give up MassEmailMessage.

 

Something share with you.

 

It happens with my mistakes.  

 

1. when I test it in Sandbox, it gives me the error that 

Mass email is not enabled for your organization or profile.  Mass email must be enabled for you to use this feature.:

 Then I checked the Setup sandbox doesn't have the permission to send mass email, thtat's quite funny. →_→!

 

2. Then I try to deploy it into the production.

 

    Then I got another error that 

First exception on row 0; first error: INVALID_ID_FIELD, Only contracts, cases, products and opportunities allowed for whatIds.: []

    My WhatIds is Contact. 

 

    It seems that I have to use SingleMailMessage. 

 

Whatever thanks for your help. 

 

It's very hard to take notice that we should limite the size, I just feel Salesforce is not smart at this point. 

ElectronElectron

Here is my new code,

 

I found it also works very well. sometime we may not need to use MassEmailMessage.

 

	for(Integer i=0; i<targetObjectIds.size();i++ ) 
	{
		If(targetObjectIds[i]!=null)
		{
		    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		    mail.setTargetObjectId(targetObjectIds[i]);
		    mail.setTemplateId([SELECT id FROM EmailTemplate WHERE Name = 'updateClassOwner'].id);
		    mail.setWhatId(whatIds[i]);
		    mail.setsaveAsActivity(false);
		    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
		}
	}

 

Puja_mfsiPuja_mfsi

Hi,

Never write query inside for loop. it hits the governer limit of salesforce.If the "TargetObjectIds" length is more that 100 ,it gives error  "too many sql query 101."

And there is a limit to call "SendEmail" method.

Then you create a list of "Messaging.SingleEmailMessage" and add the indiviual email to the created list 

as:

 

String emailTemplateId = [SELECT id FROM EmailTemplate WHERE Name = 'updateClassOwner'].id;

List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();

for(Integer i=0; i<targetObjectIds.size();i++ )
{
If(targetObjectIds[i]!=null)
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(targetObjectIds[i]);
mail.setTemplateId(emailTemplateId);
mail.setWhatId(whatIds[i]);
mail.setsaveAsActivity(false);
mailList.add(mail);
}
}

Messaging.sendEmail(mailList);

 

 

ElectronElectron

Thank you so much.

 

It's my first time to know that SendEmail is one kind of Query.

Mani PenumarthiMani Penumarthi
What will be the max number of email that we can send per day  using the mass email. Will the limit varys between the single email message and mass email messages. If not what is the difference between this two?
Vijay NagarathinamVijay Nagarathinam
Hi,

I am using mass email message concept to send an email to record owner. In the code, I have queried the corresponding email template. Based on my conditions email is received. But I am not getting the merge fields that are used in the email template. Can anyone help me how to resolve this issue?