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
puli rajupuli raju 

send email from apex

Mahesh DMahesh D
Hi Puli Raju,

Mass Emailing

Pros
  • Is generally faster for the user (you go through a wizard once instead of once per contact.)
Cons
  • Cannot customize the email template on a per-contact basis
  • Might not be able to create a filter to select the recipients
  • Visualforce email templates cannot be used
public void SendEmail() {
 List<contact> lstcon=[Select id from contact limit 2];
 List<Id> lstids= new List<Id>();
 for(Contact c:lstcon) {
  lstids.add(c.id);
 }
 EmailTemplate et=[Select id from EmailTemplate where name = 'EmailTemplatename' limit 1];
 
 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(lstIds);
 mail.setSenderDisplayName('System Admin');
 mail.setTemplateId(et.id);
 Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}

Individual Emailing

Pros
  • Can customize the email template before sending if you select a text template
  • Does not require Extended Mail Merge to be activated
  • Does not require a filter to select recipient
Cons
  • Time consuming for a large number of emails
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'abc2@gmail.com', 'abc2@gmail.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Subject Test Message';
message.plainTextBody = 'This is the message body.';
Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

if (results[0].success) {
    System.debug('The email was sent successfully.');
} else {
    System.debug('The email failed to send: ' + results[0].errors[0].message);
}

Single email and Mass email options are avaialble both on UI and the Platform options in Salesforce. 
 
Single email in UI can be used by workflows, alerts and notifications etc, where as mass emails can be used in the UI to send mass emails to contacts and leads using a template. 
 
Through APEX we can use the same functionality with additional programming and logic. 
 
See the links below, 
 
Email Overview: 
 
https://help.salesforce.com/apex/HTViewHelpDoc?id=email.htm&language=en
 
Single email:
 
http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_sendemail.htm
 
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_forcecom_email_outbound.htm

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm
 
Mass email: 
 
https://help.salesforce.com/HTViewHelpDoc?id=email_mass.htm&language=en_US
 
https://help.salesforce.com/apex/HTViewHelpDoc?id=email_mass_notes.htm&language=en

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_mass.htm
 
Apex: 
 
http://wiki.developerforce.com/page/An_Introduction_To_Email_Services_on_Force.com

Few more useful URLs:

https://www.sundoginteractive.com/blog/five-points-to-remember-when-sending-emails-with-salesforce

http://sfdcsrini.blogspot.com/2014/11/outbound-email-services-in-salesforce.html

http://salesforceondemand.blog.com/2012/01/27/to-send-email-from-apex-using-email-template/

http://www.soliantconsulting.com/blog/2009/07/how-to-avoid-governor-limits-with-sendemail-in-apex

Please do let me know if it helps you.

Regards,
Mahesh
Amit Chaudhary 8Amit Chaudhary 8
Hi Puli Raju,

Please check below post for same
1) http://amitsalesforce.blogspot.in/search/label/Email

you can send email from code by below :-
1) SingleEmailMessage
2) MassEmailMessage

User-added image

SingleEmailMessage:
Single emails are like regular individual emails that may go to one or more addresses (to/cc/bcc), but each of these emails has the same body
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'abc@gmail.com', 'xyz@gmail.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Opt Out Test Message';
message.plainTextBody = 'This is the message body.';
Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

if (results[0].success) 
{
    System.debug('The email was sent successfully.');
} else 
{
    System.debug('The email failed to send: ' + results[0].errors[0].message);
}
Please check below post to see all other method
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

MassEmailMessage:
Mass emails typically go to a large number of addresses (currently capped to 250 per email), with personalized message bodies.
public void SendEmail()
{
 List<contact> lstcon=[Select id from contact limit 2];
 List<Id> lstids= new List<Id>();
 for(Contact c:lstcon)
 {
  lstids.add(c.id);
 }
 EmailTemplate et=[Select id from EmailTemplate where name = 'EmailTemplatename' limit 1];
 
 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(lstIds);
 mail.setSenderDisplayName('System Admin');
 mail.setTemplateId(et.id);
 Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}
Please check below post to see all other method
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_mass.htm

 
Related link
https://developer.salesforce.com/page/An_Introduction_To_Email_Services_on_Force.com 
Please let us know if this will help you

Thanks
Amit Chaudhary



 
JyothsnaJyothsna (Salesforce Developers) 
Hi Raju,

Please check the below sample code

Visualforce page
 
public with sharing class ComposeMail {


    public Attachment attach { get; set; }

    public String text1 { get; set; }

    public String subject1 { get; set; }

    public String toaddre { get; set; }
    public ComposeMail (){
    attach=new attachment();
    
     }

    public PageReference sendmai() {
        list<Messaging.singleEmailMessage> mails=new list<Messaging.SingleEmailMessage>();
    Messaging.singleEmailMessage mail=new Messaging.SingleEmailMessage();
    list<String> toadd=new List<String>();
    for(string eachemail:toaddre.split(','))
    {
    toadd.add(eachemail);
    }
   //file attachment
     list<Messaging.EmailFileAttachment> lstefa = new list<Messaging.EmailFileAttachment>();
   
    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    
    efa.setfilename(attach.name);
    efa.setinline(true);
    efa.setbody(attach.body);
    lstefa.add(efa);
    mail.setfileattachments(lstefa);
    mail.setToAddresses(toadd);
    system.debug(toadd);
    mail.setSubject(subject1);
    mail.setPlainTextBody(text1);
    mails.add(mail);
   messaging.sendEmail(mails);
    
        return null;
    }

}


Controller
 
<apex:page controller="ComposeMail">
  <apex:form >
 <style>
 .fileType {
    display: block;
    position: relative;
    width: 200px;
    margin: auto;
    cursor: pointer;
    border: 0;
    height: 60px;
    border-radius: 5px;
    outline: 0;
}
.fileType:hover:after {
    background: #FF1111;
}
.fileType:after {
    transition: 200ms all ease;
    border-bottom: 3px solid rgba(0,0,0,.2);
    background: #000000;
    background-image:url('http://i.stack.imgur.com/CVpp3.jpg');
    text-shadow: 0 2px 0 rgba(0,0,0,.2);
    color: #fff;
    font-size: 20px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    content: 'Upload Something';
    line-height: 60px;
    border-radius: 5px;
    }
 </style>
  <apex:pageBlock >
 <apex:pageBlockSection >
  
  <apex:pageBlockSectionItem >
   To Addresses<apex:inputText value="{!toaddre}"/>
   </apex:pageBlockSectionItem><br/>
   
   <apex:pageBlockSectionItem >
    Subject<apex:inputText value="{!subject1}"/>
  </apex:pageBlockSectionItem><br/>
  
  <apex:pageBlockSectionItem >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <apex:inputTextarea value="{!text1}" richText="true" />
  </apex:pageBlockSectionItem>
  <!--file attachment--><br/>
  
     <apex:pageBlockSectionItem >
  <apex:inputFile fileName="{!attach.name}" value="{!attach.body}" styleclass="filetype" id="file" ></apex:inputFile>
  </apex:pageBlockSectionItem><br/>
  <apex:pageBlockSectionItem >
  <apex:outputLabel value="file" for="file"/>
   <apex:commandButton value="send" action="{!sendmai}"/>
 </apex:pageBlockSectionItem>

  </apex:pageBlockSection>
  </apex:pageBlock>
  </apex:form>
</apex:page>



User-added image
Hope this helps you!
Best Regards,
Jyothsna
David Roberts 4David Roberts 4
I've used a trigger on event and am launching a custom email template
It shows fields on contact and account but not the event. Can anyone tell me how to fox this?
{!Contact.FirstName} shows.
{!Account.BillingAddress} shows
{!Event.ActivityDate} doesn't show.
 
David Roberts 4David Roberts 4
<p>{!NullValue(Event.ActivityDate, "[should show activity date]")}</p>
gave [should show activity date]!
jaya sai prasadjaya sai prasad
Hi,
You can send email by using apex in an salesforce native app MassMailer.
MassMailer
lets you send unlimited emails from within Salesforce, no matter which edition you use. Built on the Salesforce platform, it has all the mass email features you’ll ever need.
  • Send unlimited emails no matter how large your email list isNative Salesforce integration for a seamless experience
  • Beautiful email templates complete with HTML and text versions
  • Simple email creation wizard for point-and-click ease
  • Detailed metrics & monitoring so you’re always in the know
  • Email verification & deliverability tools to make sure your emails reach your prospects
For more details

You can refer our Developer guide 
For more details check MassMailer app 
For more details logon to massmailer.io
MitChandolaMitChandola
I want to send the email aler to users (not cntcts)  with the link https://www.medicaid.gov/federal-policy-Guidance/index.html

email template name is
cmsguildlnes 

Apex code please. 

Thank you


 
Anshul Sahu 13Anshul Sahu 13
Hi,
send email through apex
your answer here 
Please go through this link:

https://anshsupportengineer.blogspot.com/2022/12/email-send-through-apex-class.html

let me know if this help you.

Happy to help You!

Thanks,
Anshul