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
Kratos55Kratos55 

Sending Email

Hi,

 

I would like some help on sending email message. I'm relatively new to Apex and VF. Here is what I've done so far - I've created a custom button (called Mail) in a Lead page, which when clicked,  pops open a simple VisualForce form window to send an email. I have pasted below the Apex code for Email Message which I had modified based on documentation/forum:

 

 

public class SendEmailMessage {

    public String toEmail {get;set;}
    public String subject {get;set;}
    public String body {get;set;}
    
    
    private final Lead MyLead;
    public SendEmailMessage(ApexPages.StandardController controller)
    
   
    {
        this.MyLead=(Lead)controller.getRecord();
    } 
   
             
    public void sendEmail() {
        
        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toaddress = (new String[]{toEmail});
        
        //email properties
        mail.setToAddresses(toaddress);
        mail.setSubject(subject);
        mail.setUseSignature(true);
        mail.setPlainTextBody(body); 
               
        // send the email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }   
   }

 The VF code is below:

<apex:page standardcontroller="Lead" extensions="SendEmailMessage"> 

    <apex:pageBlock title="EMAIL TEST">
        <apex:form >
        <br />
            <apex:outputLabel value="To" for="To"/>:<br/>
            <apex:inputText value="{!toEmail}" id="email"/><br/><br/>
                        
            <apex:outputLabel value="Subject" for="Subject"/>:<br />     
            <apex:inputTextarea value="{!subject}" id="Subject" cols="80" /><br/><br/>
                        
            <apex:outputLabel value="Body" for="Body"/>:<br />     
            <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/><br/><br/>      
            <br /><br />
                        
            <apex:commandButton value="Send Email" action="{!sendEmail}"  />
            <apex:commandButton value="Cancel" action="{!cancel}"/> 
        
        </apex:form>
    </apex:pageBlock>
</apex:page>

I'm able to send an email when I click the Send Email button on the VF page. However here is the list of issues that I've come against :

 

1. After clicking the Send Email button, I'd like to close the popped up window. I've tried using 'onclick=window.close()'. But I'm not sure if this is the correct approach.

 

2. I'd like to populate the Subject field with the Description from the Lead page when I click on the custom button (Mail) of the particular Lead.

 

Hopefully, I've explained it properly. If anybody could guide me in the right direction, I'd appreciate it.

 

Thank you.

 

 

 

 

 

 

ShwetaSShwetaS

Hi,

 

1. You can close the window using javascript function "window.close()" and calling that function on the "onclick" event of apex:commandButton. Is using this approach creating any issue at your end.

 

2. You can use the setter method to populate the subject with the Description from the Lead page. Setter methods pass user-specified values from page markup to a controller. Any setter methods in a controller are automatically executed before any action methods.

 

For Example:

 ---------VF Page------------------

<apex:inputText id="searchText" value="{!searchText}"/>

 

--------Controller----------------

String searchText;

 public String getSearchText()

 {

 return searchText;

 }

 public void setSearchText(String s)

{

 searchText = s;

 }

 

Shweta

Salesforce Developer Support

If my answer solved your question, please mark it solved so I can help as many community members as possible!

Kratos55Kratos55

Hi Shweta,

 

Thank you for your assistance on the Send Mail task. Like you suggested - I did try the 'onclick={window.close()}'. However, that wasn't closing the pop-up window. After doing some digging around, I found out apparently 'onclick={top.close()}' works. I'm not sure if this is the correct function, nevertheless it appears to be working just fine.

 

Going back to the controller, I redid the APEX code since there were some requirement changes. For example when the email was sent, the Lead Status had to change to 'Email Sent'. And now - I'm also able to populate the subject field with Description from the Lead page. Please see code below:

 

 

public class EmailMessage {

    public String emailTo {get;set;}
    public String emailCc {get;set;}
    public String subject {get;set;}
    public String body {get;set;}
    
    private final Lead lead;

    public PageReference cancel() {
        return null;
    }

     public EmailMessage() {
       lead = [select Description, ID from Lead where id = :ApexPages.currentPage().getParameters().get('id')];
       subject = lead.Description;
          } 
   
    public void sendEmail() {
        
        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        //string to hold To Addresses
        if (emailTo != '') {
            String[] toaddress = (new String[]{emailTo});
	        //set email properties 
	        mail.setSubject(subject);
	        mail.setUseSignature(true);
	        mail.setPlainTextBody(body); 
	        mail.setTargetObjectID(lead.id);
	        mail.setToAddresses(toaddress);

	     if (emailCc != '') {
	        String[] ccaddress = (new String[] {emailCc});
	        mail.setCcAddresses(ccaddress);
	        }
	
	        // send the email
	        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});  
	        
	        lead.status = 'Email Sent';
	        Update lead;
        }           
     }   
 }

 Below is my revised VF code to accomodate the new requirements:

 

<apex:page controller="EmailMessage" tabStyle="Lead" sidebar="False" showHeader="False"> 
<apex:messages />
    <apex:form >
        <apex:pageBlock title="Forward Lead to Email Recipient." Mode="Edit">
        <apex:pageBlockSection title="Email Message" columns="1">
        
		<apex:pageBlockSectionItem >
            <apex:outputLabel value="To" for="email"/>
            <apex:outputPanel styleClass="requiredInput" layout="block">
            <apex:outputPanel styleClass="requiredBlock" layout="block"/>
                <apex:inputText value="{!emailTo}" id="email" required="True"/>
            </apex:outputPanel>
        </apex:pageBlockSectionItem>
        
		<apex:pageBlockSectionItem >
            <apex:outputLabel value="Cc" for="emailCc"/>
            <apex:inputText value="{!emailCc}" id="emailCc" />
        </apex:pageBlockSectionItem>            
        
		<apex:pageBlockSectionItem >
            <apex:outputLabel value="Subject" for="Subject"/>
            <apex:outputPanel styleClass="requiredInput" layout="block">
            <apex:outputPanel styleClass="requiredBlock" layout="block"/>
                <apex:inputTextArea cols="80" rows="1" value="{!subject}" id="Subject" required="True"/>
            </apex:outputPanel>
        </apex:pageBlockSectionItem>            
        
		<apex:pageBlockSectionItem >
            <apex:outputLabel value="" for="Body"/>
            <apex:inputTextArea cols="80" rows="10" value="{!body}" id="Body" />
        </apex:pageBlockSectionItem>
    
	</apex:pageBlockSection>
    <apex:pageBlockButtons location="Bottom">
            <apex:commandButton value="Send Email" action="{!sendEmail}" onclick="{top.close()}"/> 
            <apex:commandButton value="Cancel" action="{!cancel}" onclick="{top.close()}" /> 
    </apex:pageblockbuttons>
    </apex:pageBlock>
    </apex:form>
</apex:page>

 

I believe at this point I have a functioning email form. However, there are a couple of things that I'd like to address:

 

1. Is there a way to define height and width of the pop-up window?

 

2. Even though the To field of the email form says 'required = True', it apparently does not seem to be working. When I click on Send Email from the pop-window it sends the email to my id even though the To field is left blank. I'm not sure if I'm missing something or doing something wrong. Ideally, what I'd like to do is open a dialog box prompting users to enter valid email address in the To field if they omit it and try to send the email.

 

Once again, thank you for your help and guidance.

 

 

 

 

 

rmehrmeh

Hi,

 

The pop-up window you are opening, is it through javascript or simply by Visual Force Page.

 

If you are using Visual Force page, there is a button called "Window Properties", simply set your height and width there.

If using javascript do the following:

 

 

var url ;
// in the url passed below write the name of your visual page.
url = "EmailMessage";
openWind(url);

function openWind(URL)
{
curPopupWindow = window.open(URL, "_blank","width=650, height=500,dependent=no,toolbar=no,status=no,directories=no,menubar=no,scrollbars=1,resizable=no", true);
}

 For the second issue, try putting debugs and check what value it is taking for emailTo. Also apart from checking emailTo != '' also check emailTo != null before checking it empty.

It might be taking it as null rather than blank.

 

I hope this works for you.

 

Kratos55Kratos55

Hi,

 

Thank you for your feedback. Since, I'm opening the pop-up window through VF page, I did like you had suggested and changed the Height and Width through Windows Properties. That worked!!

 

Regarding the second issue, going through blogs/documentation, it appears the 'requiredness' works only with InputField as opposed to InputText which I have on my VF page. However, when I tried experimenting using InputField instead of InputText, I get an error message saying that it works with sObjects only. I'm still trying to figure out a workaround so that it could work with InputText.

 

I've even tried to use the addError method to generate a custom error message from the server side. However, I'm not sure if this is an effecient route to take.

 

Once again, thanks for all your help. Still on the learning curve :-)

 

 

rmehrmeh

Hi,

 

You are absolutely right, the required attribute only works in case of inputfield.

Note you can use inputfield when you use standardcontroller="sObject" (some sObject) which you have not used on your page, that is the reason you are getting an error while you are using inputfield.

 

So the work around when you are using inputText can be try using some css. Please have a look at the sample code below. 

 

<span class="requiredInput" style="padding: 3px 0px 3px 0px;text-align:left;valign:middle" >
   <div class="requiredBlock"></div>								             <apex:inputText value="{!emailTo}" id="email"/>
</span>

Once you are done with this, an important point to note is that the required validation wont happen automatically.

On the "Send Email" button, you need to write a javascript to check whether there is a value in the email text box, and if an appropriate value is found then only link your action to it.

 

Please try doing the above and check if it works for you.

 

 

Kratos55Kratos55

Hi,

 

Here is what I've done so far.

 

- Created a CSS file under Static Resources like you had suggested.

- Modified the code in VF.  I have pasted only the top portion of the VF code with the header and the JavaScript. Please see below:

 

 

<apex:page standardcontroller="Lead" extensions="SendEmail" sidebar="False" showHeader="False">
   <apex:stylesheet value="{!$Resource.EmailCSS}"/> 

    <script type="text/javascript">
        function validate() {
       if ( "{!emailTo}" == " " )
            {
              alert ( "Enter Email Address" );
              valid = false;
            }
        return valid;
            }
    </script>

 

On the Send Mail button, I've tweaked the code to include the validate() on the 'onclick' function:

 

<apex:commandButton value="Send Email" action="{!sendEmail}" onclick="{validate()}" onclick="{top.close()}"/> 

 

The validation still does not seem to work. I'm not sure what I'm missing or doing incorrectly over here.

 

In the meantime, I went back to the drawing board and tweaked the APEX class to reference standard controller in VF. I realized when creating a custom button with a custom controller, the VF page does not show up in the Content Source. Correct me if I'm wrong - wouldn't I need to use standard controllers for this?

 

Thank you for your help.

 

 

 

rmehrmeh

Hi,

 

First of all, by including the css are you able to get the "required" attribute.

If it is getting displayed, don't change your code else do the same as below

 

 

<span class="requiredInput" style="padding: 3px 0px 3px 0px;text-align:left;valign:middle" >
<div class="requiredBlock"></div>
<apex:inputText value="{!emailTo}" id="email" required="True"/>
</span>

 Secondly, for the javascript part i dont think 2 onclicks will work at the same time and also write your javascript as below (In your javascript code also you are returning a value, but while calling the javascript you aren't returning anything.):

 

 

<apex:commandButton value="Send Email" onclick="javascript&colon; return validate()" action="{!sendEmail}"/> 

 Third in your javascript code, since "{!emailTo}" is a string variable, also put a null check apart from empty check.

After making the above changes the javascript should work.

Also do read about actionFunction, I think it might work better for your code on commandButton i.e. once you validate the email, then only you need to call your "sendEmail" action.

 

And Last, you are absolutely right, the content source wont show up if you dont use Standard Controller for your VisualForce Page. You definitely need to use standard controllers.

 

Try and check it out!!

 

 

 

Kratos55Kratos55

Thank you for your comments earlier.

In the CSS file, I had not specified 'required=true' earlier. This minor change has been added to the CSS file. I have modified the JavaScript code to include NULL in the condition. Please see below:

<script type="text/javascript">
    function validate() {
       if ( "{!emailTo}" == " "  && "{!emailTo}" == null)
    {
        alert ( "Enter Email Address" );
        valid = false;
    }
    return valid;
}
</script>


As for the command line button, I have modified like you had suggested as follows:

 

<apex:commandButton value="Send Email" onclick="javascript&colon; return validate()" action="{!sendEmail}"/> 


Just to verify if the JavaScript function is actually being called, I just tested it with the alert message only, commenting out the IF condition. The alert message, predictably, pops-up when no email address is entered in the TO field.

 

When I un-comment the IF condition, it merely validates the field (if we could call it such), and does not send the email if the TO field is missing. However, the pop-up alert does not show. I hope I have explained it properly.

Am I doing something incorrectly in the JavaScript, or do I need to do something else with my Send Email button?

Thanks for your help and patience.

rmehrmeh

Hi,

 

Please make a note whenever you are checking a property as null, please put a boolean operator as ||.

That is one mistake i find in your code. Please check the below code for changes:

   Note: I have put alerts in the javascript to check what values they are taking, you might need to alter your code accordingly

 

 

<script type="text/javascript">
function validate()
{
alert('TO address=======' +"{!emailTo}");
if("{!emailTo}" == '' || "{!emailTo}" == null)
{
alert('Enter Email Address');
valid = false;
}
else
{
valid = true;
}
alert('valid==========' +valid);
// if valid == true doesnt work right then try and use valid == 'true'.
if(valid == true)
{
// apart from using command button, use <apex:actionFunction> to invoke your action after checking whether email To is entered or not.
validateEmail(); //name of your action Function which will invoke your action.
} return valid; } </script>

 

 

Also in the last post i had mentioned, try and make use of commandButton, this will solve your purpose. I am writing the code snippet to help you understand better:

 

 

<apex:commandButton value="Send Email" onclick="javascript&colon; return validate"/>
<apex:actionFunction name="validateEmail" action="{!sendEmail}" rerender="Assign a id to your PageBlock and mention the id here"/>

 If you have any further doubts, please do write.

Thanks.

 

Kratos55Kratos55

Sorry for getting back a little late on this since I was held up on another project. Here is something that I was trying to see if the the Javascript code was working properly or not (stripped down code)

<script type="text/javascript">   
    function validate()   
    {       
        //alert('TO address =  ' +"{!emailTo}");  
          if ("{!emailTo}" == 'xyz@domain.com'){
            alert ('Enter valid email address');
            return false;  
        }
     }   
 </script>  

 

1. Here the first alert works (note I commented this later), which means the function is getting called and the email value is getting passed into it.

 

2. If I hardcode a test email address in the To field and submit the form, the conditional statement does not return false, which means I'm probably hitting a roadblock on the IF statement. Please correct me if my assumptions are wrong.

 

Appreciate your help and patience,

 

 

rmehrmeh

Hi,

 

Are you setting the emailTo field as 'xyz@domain.com' when you are submitting the form.

If Yes, then only you will hit the return false and also the alert message.

 

I would suggest put an else statement and put an alert to check in which block your alert for 'To Address' is going.