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
RiverChaserRiverChaser 

Sending Email Using MassEmailMessage

I am having trouble sending email using MassEmailMessage. At this point I am only sending a single email to one contact, but MassEmailMessage seems to be the only way to programmatically send an email using an existing template.

I'm using the code below in an s-control attached to a button on the Contact form, and everything seems to run fine. The alert() pops up a message that says {success:'true',}, and the resulting page says Email sent! as shown in the code. If I look at Setup | Monitoring | Mass Email Monitoring, the send is shown there as successful. But the email never arrives. (For testing, I'm sending it to myself. No, it's not in my spam filter.)

I am able to use SingleEmailMessage with no problem.

What am I doing wrong? Thanks for any pointers!

Don

Code:
<html>
   <head>
   <script src="/soap/ajax/10.0/connection.js" type="text/javascript"></script>
   <script>
      var contactId = "{!Contact.Id}";
      function sendEmail() {
            var result = "";
            try {
                        var templResp = sforce.connection.query("select id from emailtemplate where name = 'Welcome!'");
                        var templateID = templResp.getArray("records")[0].Id;
                        var mass = new sforce.MassEmailMessage();
            
                        mass.replyTo = "donkiely@computer.org";
                        mass.subject = "Mass Email from SF!";
                        var a = new Array(1);
                        a[0] = contactId;
                        mass.targetObjectIds = a;
                        mass.saveAsActivity = true;
                        mass.templateId = templateID;
                        var sendMailRes = sforce.connection.sendEmail([mass]);
                        
                        alert(sendMailRes);

                     output.innerHTML = "Email sent! " + "result: " + result;
            } catch(error) {
                        output.innerHTML = error + ":result = " + result;
            }
      }
   </script>
   <body onload="sendEmail()">
      <div id="output"></div>
   </body>
</html>

Message Edited by RiverChaser on 09-09-2007 12:30 PM

Best Answer chosen by Admin (Salesforce Developers) 
khanWebgurukhanWebguru
blank_page

Dear All,

 

 I have an email template which is given below:

 

Evaluation Request from {!Lead.LastName} {!Lead.FirstName} for {!Lead.SupportProduct__c}, is pending and requires manual approval. <br/>

Click <a href="{!ApprovalRequest.Internal_URL}">here</a> to approve or reject this request.<br/><br/>

Thanks.

 

Whenever I use this template through "Approval Processes" it works fine. But I have different situation in which I cannot use "Approval Processes". For example I need that when a Lead create then email should be generate for Lead Approval and send to those receptionist that are belongs to selected region. If a lead belongs to ASIA then email should be send on asia@abc.com or if region is USA then it should be for usa@abc.com I successfully completd this task with static or just text base template. But whenever I use Customise template its not filling merge values. Following is TRIGER code:

 

trigger TestEmail on Lead (after insert)
{       
            MailerUtils.sendMail(Trigger.new[0].Region__c, String.valueOf(Trigger.new[0].Id), Trigger.new  [0].IsEmbargoe__c);


 

 

Now, following is MailerUtils class having sendMail method

 

public class MailerUtils
{
 
    public static void sendMail(string location, string leadId, Boolean IsEmbargoe)
    {
        string message;
        string temp = 'ApproveLeadTemplate';
        String[] toAddresses;
        List<Id> idsList = getEmailAddresses(location);
       
        if(IsEmbargoe == False)
        {
            temp = 'ApproveEmbargoeTemplate';
        }
        EmailTemplate e = [select Id,Name,Subject,body from EmailTemplate where name like :temp+'%'];
                                                  
        if(e != null || idsList==null)
        {
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.saveAsActivity = false;
   
            mail.setTargetObjectIds(idsList);
            mail.setTemplateId(e.Id);
           
            mail.setUseSignature(false);
            mail.setSaveAsActivity(false);


            // Send the email
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
          
        }
        else
        {
            Messaging.SingleEmailMessage mail1 = new Messaging.SingleEmailMessage();
            toAddresses = new String[] {'khan@abc.com'};
            mail1.setToAddresses(toAddresses);
            message = 'This email will recieve by you only if Template Not Found!!!';
            mail1.setHtmlBody(message);
        }
                
            }  
   
     public static List<Id> getEmailAddresses(string groupName)
     {

        List<String> idList = new List<String>();
       
        List<Id> mailToIds = new List<Id>();
       
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupName];
       
        for (GroupMember gm : g.groupMembers) {
       
        idList.add(gm.userOrGroupId);
       
        }
       
        User[] usr = [SELECT Id, email FROM user WHERE id IN :idList];
       
        for(User u : usr) {
       
        mailToIds.add(u.Id);
       
        }
       
        return mailToIds;
       
    }
   

 

 

I have some public group having same name like ASIA, USA and Austrailia so that this help me to pull autmatic all user from selected group on the bases of Region.

 

But In all this I am having problem that the dynamic fields or u can say merge fields are not filling please help me in this context. Thanking in advance for you help.

 

Regards,

 

Asif Ahmed Khan

Sr. Software Eng.

Palmchip :)

All Answers

RiverChaserRiverChaser
D'oh!!! I'm guessing that you can't send mass emails from a sandbox. That is why everything seemed to be working, including the monitoring update, but I wasn't getting the email.

When I copied the exact same code into a new s-control in the production instance, it worked great.

This is a drag though, since I sure would like to test stuff like this in a safe environment. Oh well.

Don
ShamSham
Did you try after sending mail after. setting SaveAsActivity as false.
RiverChaserRiverChaser
Yes, I did. Same result except, of course, the email doesn't show up in the Activity History.

Don
gsickalgsickal
Your organization must be configured to support mass emails.  See help for "sending mass email" and this will show you how to configure the settings so your mails are actually sent and received.
RiverChaserRiverChaser
gsikal:

Thanks, but I don't see any information in the Sending Mass Emails about configuring my organization for using mass emails. The help topic describes how to send them, but not configure it?

But since I already CAN send mass emails from my organization, is there something I have to do in the sandbaox to enable it?

What am I missing?

Thanks,
Don
gsickalgsickal
Not sure, I forgot you were talking about the sandbox.  It is possible mass emails are not possible in the sandbox environment.  You might want to post a case support question on this to see how to enable this, if it can be.
khanWebgurukhanWebguru
blank_page

Dear All,

 

 I have an email template which is given below:

 

Evaluation Request from {!Lead.LastName} {!Lead.FirstName} for {!Lead.SupportProduct__c}, is pending and requires manual approval. <br/>

Click <a href="{!ApprovalRequest.Internal_URL}">here</a> to approve or reject this request.<br/><br/>

Thanks.

 

Whenever I use this template through "Approval Processes" it works fine. But I have different situation in which I cannot use "Approval Processes". For example I need that when a Lead create then email should be generate for Lead Approval and send to those receptionist that are belongs to selected region. If a lead belongs to ASIA then email should be send on asia@abc.com or if region is USA then it should be for usa@abc.com I successfully completd this task with static or just text base template. But whenever I use Customise template its not filling merge values. Following is TRIGER code:

 

trigger TestEmail on Lead (after insert)
{       
            MailerUtils.sendMail(Trigger.new[0].Region__c, String.valueOf(Trigger.new[0].Id), Trigger.new  [0].IsEmbargoe__c);


 

 

Now, following is MailerUtils class having sendMail method

 

public class MailerUtils
{
 
    public static void sendMail(string location, string leadId, Boolean IsEmbargoe)
    {
        string message;
        string temp = 'ApproveLeadTemplate';
        String[] toAddresses;
        List<Id> idsList = getEmailAddresses(location);
       
        if(IsEmbargoe == False)
        {
            temp = 'ApproveEmbargoeTemplate';
        }
        EmailTemplate e = [select Id,Name,Subject,body from EmailTemplate where name like :temp+'%'];
                                                  
        if(e != null || idsList==null)
        {
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.saveAsActivity = false;
   
            mail.setTargetObjectIds(idsList);
            mail.setTemplateId(e.Id);
           
            mail.setUseSignature(false);
            mail.setSaveAsActivity(false);


            // Send the email
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
          
        }
        else
        {
            Messaging.SingleEmailMessage mail1 = new Messaging.SingleEmailMessage();
            toAddresses = new String[] {'khan@abc.com'};
            mail1.setToAddresses(toAddresses);
            message = 'This email will recieve by you only if Template Not Found!!!';
            mail1.setHtmlBody(message);
        }
                
            }  
   
     public static List<Id> getEmailAddresses(string groupName)
     {

        List<String> idList = new List<String>();
       
        List<Id> mailToIds = new List<Id>();
       
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupName];
       
        for (GroupMember gm : g.groupMembers) {
       
        idList.add(gm.userOrGroupId);
       
        }
       
        User[] usr = [SELECT Id, email FROM user WHERE id IN :idList];
       
        for(User u : usr) {
       
        mailToIds.add(u.Id);
       
        }
       
        return mailToIds;
       
    }
   

 

 

I have some public group having same name like ASIA, USA and Austrailia so that this help me to pull autmatic all user from selected group on the bases of Region.

 

But In all this I am having problem that the dynamic fields or u can say merge fields are not filling please help me in this context. Thanking in advance for you help.

 

Regards,

 

Asif Ahmed Khan

Sr. Software Eng.

Palmchip :)

This was selected as the best answer
khanWebgurukhanWebguru
Dear All,

 

 I have an email template which is given below:

 

Evaluation Request from {!Lead.LastName} {!Lead.FirstName} for {!Lead.SupportProduct__c}, is pending and requires manual approval. <br/>

Click <a href="{!ApprovalRequest.Internal_URL}">here</a> to approve or reject this request.<br/><br/>

Thanks.

 

Whenever I use this template through "Approval Processes" it works fine. But I have different situation in which I cannot use "Approval Processes". For example I need that when a Lead create then email should be generate for Lead Approval and send to those receptionist that are belongs to selected region. If a lead belongs to ASIA then email should be send on asia@abc.com or if region is USA then it should be for usa@abc.com I successfully completd this task with static or just text base template. But whenever I use Customise template its not filling merge values. Following is TRIGER code:

 

trigger TestEmail on Lead (after insert)
{       
            MailerUtils.sendMail(Trigger.new[0].Region__c, String.valueOf(Trigger.new[0].Id), Trigger.new  [0].IsEmbargoe__c);


 

 

Now, following is MailerUtils class having sendMail method

 

public class MailerUtils
{
 
    public static void sendMail(string location, string leadId, Boolean IsEmbargoe)
    {
        string message;
        string temp = 'ApproveLeadTemplate';
        String[] toAddresses;
        List<Id> idsList = getEmailAddresses(location);
       
        if(IsEmbargoe == False)
        {
            temp = 'ApproveEmbargoeTemplate';
        }
        EmailTemplate e = [select Id,Name,Subject,body from EmailTemplate where name like :temp+'%'];
                                                  
        if(e != null || idsList==null)
        {
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.saveAsActivity = false;
   
            mail.setTargetObjectIds(idsList);
            mail.setTemplateId(e.Id);
           
            mail.setUseSignature(false);
            mail.setSaveAsActivity(false);


            // Send the email
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
          
        }
        else
        {
            Messaging.SingleEmailMessage mail1 = new Messaging.SingleEmailMessage();
            toAddresses = new String[] {'khan@abc.com'};
            mail1.setToAddresses(toAddresses);
            message = 'This email will recieve by you only if Template Not Found!!!';
            mail1.setHtmlBody(message);
        }
                
            }  
   
     public static List<Id> getEmailAddresses(string groupName)
     {

        List<String> idList = new List<String>();
       
        List<Id> mailToIds = new List<Id>();
       
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = :groupName];
       
        for (GroupMember gm : g.groupMembers) {
       
        idList.add(gm.userOrGroupId);
       
        }
       
        User[] usr = [SELECT Id, email FROM user WHERE id IN :idList];
       
        for(User u : usr) {
       
        mailToIds.add(u.Id);
       
        }
       
        return mailToIds;
       
    }
   

 

 

I have some public group having same name like ASIA, USA and Austrailia so that this help me to pull autmatic all user from selected group on the bases of Region.

 

But In all this I am having problem that the dynamic fields or u can say merge fields are not filling please help me in this context. Thanking in advance for you help.

 

Regards,

 

Asif Ahmed Khan

Sr. Software Eng.

Palmchip Pvt Ltd.