Monday, 24 February 2014

Outbound Emails in salesforce

To send individual and mass email with Apex, use the following classes:
SingleEmailMessage
Instantiates an email object used for sending a single email message. The syntax is:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
MassEmailMessage
Instantiates an email object used for sending a mass email message. The syntax is:
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
Messaging
Includes the static sendEmail method, which sends the email objects you instantiate with either the SingleEmailMessage or MassEmailMessage classes, and returns a SendEmailResult object.
The syntax for sending an email is:
Messaging.sendEmail(new Messaging.Email[] { mail } , opt_allOrNone);
where Email is either Messaging.SingleEmailMessage or Messaging.MassEmailMessage.
The optional opt_allOrNone parameter specifies whether sendEmail prevents delivery of all other messages when any of the messages fail due to an error (true), or whether it allows delivery of the messages that don't have errors (false). The default is true.
Includes the static reserveMassEmailCapacity and reserveSingleEmailCapacity methods, which can be called before sending any emails to ensure that the sending organization won't exceed its daily email limit when the transaction is committed and emails are sent. The syntax is:
Messaging.reserveMassEmailCapacity(count);
and
Messaging.reserveSingleEmailCapacity(count);
where count indicates the total number of addresses that emails will be sent to.
Note the following:
  • The email is not sent until the Apex transaction is committed.
  • The email address of the user calling the sendEmail method is inserted in the From Address field of the email header. All email that is returned, bounced, or received out-of-office replies goes to the user calling the method.
  • Maximum of 10 sendEmail methods per transaction. Use the Limits methods to verify the number of sendEmail methods in a transaction.
  • Single email messages sent with the sendEmail method count against the sending organization's daily single email limit. When this limit is reached, calls to the sendEmail method using SingleEmailMessage are rejected, and the user receives a SINGLE_EMAIL_LIMIT_EXCEEDED error code. However, single emails sent through the application are allowed.
  • Mass email messages sent with the sendEmail method count against the sending organization's daily mass email limit. When this limit is reached, calls to the sendEmail method using MassEmailMessage are rejected, and the user receives a MASS_MAIL_LIMIT_EXCEEDED error code.
  • Any error returned in the SendEmailResult object indicates that no email was sent.

Example

// First, reserve email capacity for the current Apex transaction to ensure
                        
// that we won't exceed our daily email limits when sending email after
                        
// the current transaction is committed.
Messaging.reserveSingleEmailCapacity(2);

// Processes and actions involved in the Apex transaction occur next,
// which conclude with sending a single email.

// Now create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

// Strings to hold the email addresses to which you are sending the email.
String[] toAddresses = new String[] {'user@acme.com'}; 
String[] ccAddresses = new String[] {'smith@gmail.com'};
  

// Assign the addresses for the To and CC lists to the mail object.
mail.setToAddresses(toAddresses);
mail.setCcAddresses(ccAddresses);

// Specify the address used when the recipients reply to the email. 
mail.setReplyTo('support@acme.com');

// Specify the name used as the display name.
mail.setSenderDisplayName('Salesforce Support');

// Specify the subject line for your email address.
mail.setSubject('New Case Created : ' + case.Id);
 
//Required if using a template, optional otherwise. The ID of the contact, lead, or user to 
//which the email will be sent. The ID you specify sets the context and 
//ensures that merge fields in the template contain the correct data.
mail.SetTargetObjectId(userId); 
 
 // Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);

// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);

// Specify the text content of the email.
mail.setPlainTextBody('Your Case: ' + case.Id +' has been created.');

mail.setHtmlBody('Your case:<b> ' + case.Id +' </b>has been created.<p>'+
     'To view your case <a href=https://na1.salesforce.com/'+case.Id+'>click here.</a>');

// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

How to send mass emails to users in salesforce

In the below sample code "lstPortalUser" is a list of partner users.Now I need to sent them an email with different body.

  1. List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();  
  2. for(User portalUser :lstPortalUser)  
  3. {     
  4.    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
  5.    string body = 'Hi '+ portalUser.LastName;    
  6.    mail.setSubject('Test Subject');  
  7.    mail.setTargetObjectId(portalUser.Id);  
  8.    mail.setSaveAsActivity(false);  
  9.    mail.setHtmlBody(body);  
  10.    mails.add(mail);  
  11. }  
  12. Messaging.sendEmail(mails);  

Link to download Force.com Explorer

Note: Before downloading Force.com Explorer, kindly download and install Adobe AIR.

Use the below link to download Force.com Explorer

http://wiki.developerforce.com/page/ForceExplorer


Thursday, 6 February 2014

How Salesforce 18 Digit Id Is Calculated

As we know that each record Id represents a unique record within an organization. There are two versions of every record Id in salesforce :
  • 15 digit case-sensitive version which is referenced in the UI
  • 18 digit case-insensitive version which is referenced through the API
The last 3 digits of the 18 digit Id is a checksum of the capitalization of the first 15 characters, this Id length was created as a workaround to legacy system which were not compatible with case-sensitive Ids. The API will accept the 15 digit Id as input but will always return the 18 digit Id.
Now how we can calculate the 18 digit Id from 15 digit Id ??? Just copy paste the below code in system logs and pass your 15 digit id in String id
//Your 15 Digit Id
String id= '00570000001ZwTi' ;

string suffix = '';
integer flags;

for (integer i = 0; i < 3; i++)
{
 flags = 0;
 for (integer j = 0; j < 5; j++)
 {
  string c = id.substring(i * 5 + j,i * 5 + j + 1);
  //Only add to flags if c is an uppercase letter:
  if (c.toUpperCase().equals(c) && c >= 'A' && c <= 'Z')
  {
   flags = flags + (1 << j);
  }
 }
 if (flags <= 25)
 {
  suffix = suffix + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(flags,flags+1);
 }
 else
 {
  suffix = suffix + '012345'.substring(flags-25,flags-24);
 }
}

//18 Digit Id with checksum
System.debug(' ::::::: ' + id + suffix) ;
This debug will return the 18 digit Id.
 If you don’t mind using up a field per object….you can create a formula field to show the 18 digit ID as well.
Implementing 15-to-18-character ID converter through a formula field is below. No code needed! 
Id & 
MID( 
"ABCDEFGHIJKLMNOPQRSTUVWXYZ012345", 
MIN(FIND(MID(Id, 5, 1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 1) * 16 + 
MIN(FIND(MID(Id, 4, 1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 1) * 8 + 
MIN(FIND(MID(Id, 3, 1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 1) * 4 + 
MIN(FIND(MID(Id, 2, 1), "ABCDEFG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