Send Email to all Account related contacts

This  is working example of Email to Account related Contacts in Visualforce Page
For this code to work you need to concatenate your url with Account id.

<apex:page controller="sendEmail">
<apex:messages />
<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.Contacts}" var="contact" border="1">
<apex:column >
<apex:facet name="header">Name</apex:facet>
{!contact.Name}
</apex:column>
<apex:column >
<apex:facet name="header">Email</apex:facet>
{!contact.Email}
</apex:column>
</apex:dataTable>
<apex:form >
<br /><br />
<apex:outputLabel value="Subject" for="Subject"/>:<br />
<apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
<br /><br />
<apex:outputLabel value="Body" for="Body"/>:<br />
<apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/>
<br /><br /><br />
<apex:commandButton value="Send Email" action="{!send}" />
</apex:form>
</apex:pageBlock>
</apex:page>

//Controller
public class sendEmail {
public String subject { get; set; }
public String body { get; set; }
private final Account account;
// Create a constructor that populates the Account object
public sendEmail() {
account = [select Name, (SELECT Contact.Name, Contact.Email FROM Account.Contacts)
from Account where id =:ApexPages.currentPage().getParameters().get('id')];
}
public Account getAccount() {
return account;
}
public PageReference send() {
// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String addresses;
if (account.Contacts[0].Email != null)
{
addresses = account.Contacts[0].Email;
// Loop through the whole list of contacts and their emails
for (Integer i = 1; i < account.Contacts.size(); i++)
{
if (account.Contacts[i].Email != null)
{
addresses += ':' + account.Contacts[i].Email;
}
}
}
String[] toAddresses = addresses.split(':', 0);
// Sets the paramaters of the email
email.setSubject( subject );
email.setToAddresses( toAddresses );
email.setPlainTextBody( body );
// Sends the email
Messaging.SendEmailResult [] r =
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
return null;
}
}

Comments

  1. Stainless Steel Bikes - TITanium Art
    Classic buy metal online and classic, titanium titanium glasses frames bikes, from Classic and classic. Includes a model 1 in stock ridge wallet titanium and a model 2 titanium cup in a plastic case. iron titanium token

    ReplyDelete

Post a Comment

Popular posts from this blog

Lightning table with multiple checkbox select options and filter table data.

Lightning DataTable Working Example

Wrapper Class Example with multiple delete options