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
Dhananjaya BulugahamulleDhananjaya Bulugahamulle 

How do you send a email on apex?

I found a code for sending email from apex. The problem is it have a part i do not want. If i remove below part it wont work. Any idea how to remove below part (div Id= "Remove Part"). Thanks 

VF Page 
<div Id= "Remove Part">
<apex:pageBlock title="Send an Email to Your {!account.name} Representatives">
    <p>Fill out the fields below to test how you might send an email to a user.</p><br />
        <apex:dataTable value="{!account.AccountTeamMembers}" var="contact" border="1">
            <apex:column ><apex:facet name="header">Name</apex:facet>{!contact.user.Name}</apex:column>
            <apex:column ><apex:facet name="header">Email</apex:facet>{!contact.user.Email}</apex:column>
        </apex:dataTable>
</div>
        <apex:commandButton value="Send Email" action="{!send}" /> 
</apex:pageBlock>

Extension 
public class gibco {
    
    public Product_Brief__c pb {get;set;}
    public User u {get;set;}
    
    private ApexPages.StandardController controller {get;set;}
    public boolean bUpdate {get;set;}
    public string loggedinUserId = UserInfo.getUserId();
    public User u2 = [Select ContactId From User where Id =: '005R0000001Y6h4'];
    
    public String ctId{
        get {
             ctId = u2.ContactId;
             return ctId;
            }
        set;
    }
         
    Contact ct = [SELECT AccountId, Name FROM Contact WHERE id=:ctId];
    Account acname = [SELECT Name FROM Account WHERE id=:ct.AccountId];
    public string getacct(){
        Account acct = [SELECT Name FROM Account WHERE id=:ct.AccountId];  
        return acct.Name;
        return null;
        }
         
    Opportunity opp = [SELECT Id FROM Opportunity WHERE AccountId=:ct.AccountId LIMIT 1];
    
 /* ********************* Email ************************* */
    public String subject { get; set; }
    public String body { get; set; }
    private Account account;

    public Account getAccount() {
    account = [select Name, (SELECT user.Name, user.email from AccountTeamMembers) 
                from Account where id = :ct.AccountId];
        return account;
    }

    public PageReference send() {
        // Define the email
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
         
        
    String addresses;
    if (account.AccountTeamMembers[0].user.Email != null)
    {
        addresses = account.AccountTeamMembers[0].user.Email;
        // Loop through the whole list of contacts and their emails
        for (Integer i = 1; i < account.AccountTeamMembers.size(); i++) 
        {
            if (account.AccountTeamMembers[i].user.Email != null)
            {
                addresses += ':' + account.AccountTeamMembers[i].user.Email;
            }
        }
    }

        String[] toAddresses = addresses.split(':', 0);

        // Sets the paramaters of the email
        email.setSubject( 'New Media/Buffer Product Brief from '  + ct.Name + ' at ' + acname.Name);
        email.setToAddresses( toAddresses );
        String htmlBody= 'Dear ' + ct.Name + ':<br/><br/>';
                htmlBody += 'This is a reminder that your review of ' + ct.Name + ' for the position of ' + 
                    ct.Name + ' has not been completed yet. Please complete this review as soon as possible.' +
                    '<br/><br/>Review Link: <a href=https://cs2.salesforce.com/' + ApexPages.currentPage().getParameters().get('id') + '>click here</a><br/><br/>Thank You,<br/>Recruiting Dept.';
                email.setHtmlBody(htmlBody);
    
        // Sends the email
        Messaging.SendEmailResult [] r = 
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm,'The Product Breif has been submitted successfully. Thank you'));
        return null;
    }

 
Best Answer chosen by Dhananjaya Bulugahamulle
Vivek DeshmaneVivek Deshmane
Hi,
Remove page code and Try thid below code ,Let me know if it works.
public class gibco {
    
    public Product_Brief__c pb {get;set;}
    public User u {get;set;}
    
    private ApexPages.StandardController controller {get;set;}
    public boolean bUpdate {get;set;}
    public string loggedinUserId = UserInfo.getUserId();
    public User u2 = [Select ContactId From User where Id =: '005R0000001Y6h4'];
    
    public String ctId{
        get {
             ctId = u2.ContactId;
             return ctId;
            }
        set;
    }
         
    Contact ct = [SELECT AccountId, Name FROM Contact WHERE id=:ctId];
    Account acname = [SELECT Name FROM Account WHERE id=:ct.AccountId];
    public string getacct(){
        Account acct = [SELECT Name FROM Account WHERE id=:ct.AccountId];  
        return acct.Name;
        return null;
        }
         
    Opportunity opp = [SELECT Id FROM Opportunity WHERE AccountId=:ct.AccountId LIMIT 1];
    
 /* ********************* Email ************************* */
    public String subject { get; set; }
    public String body { get; set; }
    private Account account;

    public Account getAccount() {
    account = [select Name, (SELECT user.Name, user.email from AccountTeamMembers) 
                from Account where id = :ct.AccountId];
        return account;
    }

    public PageReference send() {
        // Define the email
		getAccount();//Here is Fix
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
         
        
    String addresses;
    if (account.AccountTeamMembers[0].user.Email != null)
    {
        addresses = account.AccountTeamMembers[0].user.Email;
        // Loop through the whole list of contacts and their emails
        for (Integer i = 1; i < account.AccountTeamMembers.size(); i++) 
        {
            if (account.AccountTeamMembers[i].user.Email != null)
            {
                addresses += ':' + account.AccountTeamMembers[i].user.Email;
            }
        }
    }

        String[] toAddresses = addresses.split(':', 0);

        // Sets the paramaters of the email
        email.setSubject( 'New Media/Buffer Product Brief from '  + ct.Name + ' at ' + acname.Name);
        email.setToAddresses( toAddresses );
        String htmlBody= 'Dear ' + ct.Name + ':<br/><br/>';
                htmlBody += 'This is a reminder that your review of ' + ct.Name + ' for the position of ' + 
                    ct.Name + ' has not been completed yet. Please complete this review as soon as possible.' +
                    '<br/><br/>Review Link: <a href=https://cs2.salesforce.com/' + ApexPages.currentPage().getParameters().get('id') + '>click here</a><br/><br/>Thank You,<br/>Recruiting Dept.';
                email.setHtmlBody(htmlBody);
    
        // Sends the email
        Messaging.SendEmailResult [] r = 
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm,'The Product Breif has been submitted successfully. Thank you'));
        return null;
    }

Best Regards,
-Vivek

All Answers

Vivek DeshmaneVivek Deshmane
Please share error details.
Dhananjaya BulugahamulleDhananjaya Bulugahamulle

When i remove and click on submit i gives me,

System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!send}' in component <apex:commandButton> in page testpbtwo: Class.pbtestExtension.send Line 46
Vivek DeshmaneVivek Deshmane
Hi,
Remove page code and Try thid below code ,Let me know if it works.
public class gibco {
    
    public Product_Brief__c pb {get;set;}
    public User u {get;set;}
    
    private ApexPages.StandardController controller {get;set;}
    public boolean bUpdate {get;set;}
    public string loggedinUserId = UserInfo.getUserId();
    public User u2 = [Select ContactId From User where Id =: '005R0000001Y6h4'];
    
    public String ctId{
        get {
             ctId = u2.ContactId;
             return ctId;
            }
        set;
    }
         
    Contact ct = [SELECT AccountId, Name FROM Contact WHERE id=:ctId];
    Account acname = [SELECT Name FROM Account WHERE id=:ct.AccountId];
    public string getacct(){
        Account acct = [SELECT Name FROM Account WHERE id=:ct.AccountId];  
        return acct.Name;
        return null;
        }
         
    Opportunity opp = [SELECT Id FROM Opportunity WHERE AccountId=:ct.AccountId LIMIT 1];
    
 /* ********************* Email ************************* */
    public String subject { get; set; }
    public String body { get; set; }
    private Account account;

    public Account getAccount() {
    account = [select Name, (SELECT user.Name, user.email from AccountTeamMembers) 
                from Account where id = :ct.AccountId];
        return account;
    }

    public PageReference send() {
        // Define the email
		getAccount();//Here is Fix
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
         
        
    String addresses;
    if (account.AccountTeamMembers[0].user.Email != null)
    {
        addresses = account.AccountTeamMembers[0].user.Email;
        // Loop through the whole list of contacts and their emails
        for (Integer i = 1; i < account.AccountTeamMembers.size(); i++) 
        {
            if (account.AccountTeamMembers[i].user.Email != null)
            {
                addresses += ':' + account.AccountTeamMembers[i].user.Email;
            }
        }
    }

        String[] toAddresses = addresses.split(':', 0);

        // Sets the paramaters of the email
        email.setSubject( 'New Media/Buffer Product Brief from '  + ct.Name + ' at ' + acname.Name);
        email.setToAddresses( toAddresses );
        String htmlBody= 'Dear ' + ct.Name + ':<br/><br/>';
                htmlBody += 'This is a reminder that your review of ' + ct.Name + ' for the position of ' + 
                    ct.Name + ' has not been completed yet. Please complete this review as soon as possible.' +
                    '<br/><br/>Review Link: <a href=https://cs2.salesforce.com/' + ApexPages.currentPage().getParameters().get('id') + '>click here</a><br/><br/>Thank You,<br/>Recruiting Dept.';
                email.setHtmlBody(htmlBody);
    
        // Sends the email
        Messaging.SendEmailResult [] r = 
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm,'The Product Breif has been submitted successfully. Thank you'));
        return null;
    }

Best Regards,
-Vivek
This was selected as the best answer
Dhananjaya BulugahamulleDhananjaya Bulugahamulle
@Vivek Deshmane It works now. What did you do? I could not see any different. Thank you very much 
Vivek DeshmaneVivek Deshmane
Hi,

In page method getAccount()  will get called when we invoke account instance variable  in page and when we remove the Account then it is null becuase your initializing it in getAccount() hence I have called getAccount() in Send method and your resovled your problem,

Please mark as solutions

Best Regards,
-Vivek
Dhananjaya BulugahamulleDhananjaya Bulugahamulle
@Vivek Deshmane Thanks for the help