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
Robert BerkeleyRobert Berkeley 

Trying to send an email from Account page

Hi, I'm trying to send an email when a client's Account is 'opened'.  I have a button on the Account page with a Javascript call beneath it:
sforce.apex.execute("AccountOpenEmail","SendEmail", {id:"{!Account.Id}"});

In the APEX class being called above I then try to load a Visual Force email template to merge fields from the Account object into its HTML for the email.
global class AccountOpenEmail
{
    WebService static void SendEmail(string id) {
      Account acc = Database.query('SELECT Account.Name, (SELECT Contact.Id FROM Account.Contacts) FROM Account WHERE id = ' + id);

      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();   
      
      email.setTargetObjectId(acc.Contacts[0].Id);
      email.setTemplateId('00X11000000DkqK');
      email.setBccSender(true);
    
      Messaging.SendEmailResult [] r = Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});      
      for ( Messaging.sendEmailResult result : r ) {
           if ( !r[0].isSuccess () ) {
               System.debug ( result  );
           } else{
               ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Email Sent Successfully' );
               ApexPages.addMessage(msg);
           }
      }
    }
}

The system was telling me that I could not use an Account.Id for the setTargetObjectId call, so I got the idea to try to get the Contact.Id from the Account record.  Am I on the right tracks?

I now get the error:
{faultcode:'soapenv:Client', faultstring:'System.QueryException: unexpected token: 'IfLgJ'

Class.AccountOpenEmail.SendEmail: line 4, column 1', }


Best Answer chosen by Robert Berkeley
Robert BerkeleyRobert Berkeley
I seem to have found a solution to this through reading this discussion (https://developer.salesforce.com/forums/ForumsMain?id=906F0000000AB9U#!/feedtype=SINGLE_QUESTION_SEARCH_RESULT&id=906F00000008kdcIAA)

Seems like the Account object is not getting any relatedTo data, but you can get that data through the 'recipient' data object instead.  My Visualforce email template now looks like this:
<messaging:emailTemplate subject="Account Information" recipientType="Contact" relatedToType="Account">
<messaging:htmlEmailBody >
<html>
<body>
   <b>Account Name:</b> {!recipient.Account.Name}<br />
  <b>Login Number:</b> {!recipient.Account.Account_Number__c} <br />
  <b>Password (case sensitive):</b> {!recipient.Account.Account_P_W__c}<br />
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>

It is now merging the correct data into the email template!

All Answers

SFDC_DevloperSFDC_Devloper
Hi ,

try below code...

{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/25.0/apex.js")} 

var agree = confirm("Are you sure you want to send email?");
 
if(agree==true){ 

var result = sforce.apex.execute("AccountOpenEmail","SendEmail",{localId:"{!Account.Id}"}); 

alert(result); 

}

global class AccountOpenEmail
{
    WebService static void SendEmail(Id localId) {
      User Usr = new User();
    Usr = [SELECT Id,ContactId,Email FROM User WHERE Id = : UserInfo.getUserId()];

  
      List<Account> acc = Database.query('SELECT Account.Name, (SELECT Contact.Id FROM Account.Contacts) FROM Account WHERE id =:localId ');
      
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();   
      String[] toAddresses = new String[] {Usr.Email};
      email.setTargetObjectId(Usr.ContactId);
      email.setTemplateId('00X11000000DkqK');
      email.setSubject('Test Mail');
      email.setToAddresses(toAddresses);  
      String messageBody = '<html><body>Hi, welcome to &nbsp;&nbsp;&nbsp;Our World</body>  </html>';
      email.setHtmlBody(messageBody); 
      email.setBccSender(true);
      email.setSaveAsActivity(false);
    
      Messaging.SendEmailResult [] r = Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});       
      for ( Messaging.sendEmailResult result : r ) {
           if ( !r[0].isSuccess () ) {
               System.debug ( result  );
           } else{
               ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Email Sent Successfully' );
               ApexPages.addMessage(msg);
           }
      }
    }
}

Thanks,
Rockzz
Robert BerkeleyRobert Berkeley
Thanks for your reply Rockzz
I tried the APEX code you posted above but could not get anything from the first SOQL select.  The UserInfo.getUserId() is returning a NULL and so there's nothing in the Usr record.  I am getting record data from the 2nd SOQL select though, so using the Contact.Id from there I am able to instantiate the email template.

My problem now is that while it does now send and email (yay!) it does not merge data from the Account object into that email.  Here is the APEX code I am now using:
global class AccountOpenEmail
{
    WebService static void SendEmail(Id localId) {
      User Usr = new User();
      Usr = [SELECT Id,ContactId,Email FROM User WHERE Id = : UserInfo.getUserId()];

      List<Account> acc = Database.query('SELECT Account.Name, (SELECT Contact.Id, Contact.Email FROM Account.Contacts) FROM Account WHERE id =:localId ');
      
      System.debug( 'ID: ' + acc[0].Contacts[0].Id );
      System.debug( 'Email: ' + acc[0].Contacts[0].Email );
      //return;
  
      Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();   
      String[] toAddresses = new String[] {acc[0].Contacts[0].Email};
      email.setTargetObjectId(acc[0].Contacts[0].Id);
      email.setTemplateId('00X11000000DkqK');
      //email.setSubject('Test Mail');
      email.setToAddresses(toAddresses);  
      String messageBody = '<html><body>Hi, welcome to &nbsp;&nbsp;&nbsp;Our World</body>  </html>';
      //email.setHtmlBody(messageBody); 
      email.setBccSender(true);
      email.setSaveAsActivity(false);
    
      Messaging.SendEmailResult [] r = Messaging.SendEmail(new Messaging.SingleEmailMessage[] {email});       
      for ( Messaging.sendEmailResult result : r ) {
           if ( !r[0].isSuccess () ) {
               System.debug ( result  );
           } else{
               //ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Email Sent Successfully' );
               //ApexPages.addMessage(msg);
           }
      }
    }
}

And here is the Visual Force email template I am using:
<messaging:emailTemplate subject="Account Information" recipientType="Contact" relatedToType="Account">
<messaging:htmlEmailBody >
<html>
<body>
   <b>Account Name:</b> {!relatedTo.Name}<br />
  <b>Login Number:</b> {!relatedTo.Account_Number__c} <br />
  <b>Password (case sensitive):</b> {!relatedTo.Account_P_W__c}<br />
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>

I tried using the annotation {!Account.Name} but it complained that:
Error: Unknown property 'core.email.template.EmailTemplateComponentController.Account'
I read somewhere else in the docs that I should rather be using {!relatedTo.Name}  so I am using that instead.
Is this how you merge Account data into an email template?
Robert BerkeleyRobert Berkeley
I seem to have found a solution to this through reading this discussion (https://developer.salesforce.com/forums/ForumsMain?id=906F0000000AB9U#!/feedtype=SINGLE_QUESTION_SEARCH_RESULT&id=906F00000008kdcIAA)

Seems like the Account object is not getting any relatedTo data, but you can get that data through the 'recipient' data object instead.  My Visualforce email template now looks like this:
<messaging:emailTemplate subject="Account Information" recipientType="Contact" relatedToType="Account">
<messaging:htmlEmailBody >
<html>
<body>
   <b>Account Name:</b> {!recipient.Account.Name}<br />
  <b>Login Number:</b> {!recipient.Account.Account_Number__c} <br />
  <b>Password (case sensitive):</b> {!recipient.Account.Account_P_W__c}<br />
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>

It is now merging the correct data into the email template!
This was selected as the best answer
SFDC_DevloperSFDC_Devloper
Hi Robert,

    If this solves your problem, kindly mark it as the best answer.

Thanks,
Rockzz