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
ElcalvoMikeElcalvoMike 

Execute VF page for triggered email send

I have created a custom controller and VF page that allows me to chose a number of templates via a dropdown (thanks Bob for the help on conditional rendering) and send that page as an email (and edit before sending if needed)

 

I would like to use this same code to auto send this page from a trigger.

Is there some method for calling  a VF page and get the retuned result of it?

 

currently the controller takes the vars from the URL like /apex/display_email?id=someoppid&body=nameofcomponenet

 

controller (apologies for messy code as I fumble through this)

 

public class opportunityCustomController{ 
private final Opportunity o;
private final Tracking_Information__c tInfo;
private final string component;
private final Emails_Subject_And_Body__c objEBody;
Public string qBody{ get; set; }
Public string emailtype;
public string subject{get; set;}
public string messageBody{get; set;}
private string auto{get; set;}

public opportunityCustomController(){
        auto= Apexpages.currentPage().getParameters().get('auto');     
        o=[select ID,Name,address1__c,address2__c,shipAddrType__c,Amount_Net__c,Cancelled__c,chkAmount__c,chkNumber__c,chkRecd__c,chkDate__c,city__c,Company__c,country__c,cPONum__c,cShippingInfo__c,custID__c,CustomerArt__c,email__c,shippingemail__c,EstDelEndDate__c,EstDelStartDate__c,EstShipMethod__c,ExpectedShipDate__c,fax__c,shippingfax__c,fname__c,handling__c,InvoiceSent__c,iocd_text__c,iOrderCustDetailPk__c,IS_CC__c,Is_CreditCard_declines__c,isFromUnviersalQuote__c,isOnCreditHold__c,Lead_Time__c,lname__c,LogoUploaded__c,OrderDate__c,OrderInstructions__c,phone__c,shippingphone__c,POSent__c,PromoCode__c,rebate__c,rebate_desc__c,Redo__c,Remarks__c,ReOrder__c,shipping__c,shippingaddress__c,shippingaddress2__c,shippingcity__c,shippingcompany__c,NetShippingCost__c,shippingcountry__c,shippingfname__c,shippinglname__c,shippingstate__c,shippingtitle__c,shippingzip__c,state__c,tax__c,Title__c,VisitorId__c,WebPartner__c,webpartnerOID__c,XMQuoteNo__c,zip__c,(Select Id, IsPrimary, Contact.Name, Contact.Email From OpportunityContactRoles Where IsPrimary=TRUE)
          from Opportunity where id = : Apexpages.currentPage().getParameters().get('id')];
      component=Apexpages.currentPage().getParameters().get('body');
       tInfo=[select Adjustment_Billed__c,Adjustment_Incentive__c,AutoID__c, Billed_Charge__c,Incentive_Credit__c,
                        Opportunity__c,Receiver_Zip__c,Reference_1__c,Reference_2__c,Sender_Company_Name__c,Sender_Zip__c,
                        Service_Level__c,Shipping_Type__c,Tracking_Link__c, Tracking_Number__c,Vendor__c,Web_Order_Number__c,
                        Weight__c,Zone__c
                        from Tracking_Information__c where Web_Order_Number__c ='MPP-190'];
                        
        //qBody = String.ValueOf(Apexpages.currentPage().getParameters().get('body'));
        emailtype=String.ValueOf(Apexpages.currentPage().getParameters().get('body'));
        subject = emailtype.Replace('/','');
        
        if(auto == '1'){
            pagereference objP = send();
        }
}

public Opportunity getOpportunity(){
return o;
}

public string getEmailBody() {
return component;

}

public Tracking_Information__c getTracking(){
return tInfo;
}

public string getemailtype(){
return emailtype;
}

public string getSubject(){
return subject;
}

public string getmessageBody(){
    return messageBody;
}

public string getAutoSend() {
return auto;
}

public List<SelectOption> getItems() {
    List<SelectOption> options = new List<SelectOption>();
    options.add(new SelectOption('shippingupdate','shippingupdate'));
    options.add(new SelectOption('trackinginfo','trackinginfo'));
    return options;
}
    
public void SendEmail() {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId('003Q000000LIUOB');
mail.setTemplateId('00XQ0000000MGee');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

public PageReference send() {
    // Define the email
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    String addresses;
   // addresses = String.valueOf(o.get('email__c')); //Need to open this comment
   addresses = 'rupesh@smartsign.co.in';
    String[] toAddresses = addresses.split(':', 0);
    // Sets the paramaters of the email
    email.setSubject(subject);
    email.setToAddresses(toAddresses);
    /*email.setPlainTextBody( body );*/
    email.setHtmlBody(messageBody);
    // Sends the email
    Messaging.SendEmailResult [] r =
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    return null;
    //PageReference objPage = new PageReference(Apexpages.currentPage().getParameters().get('retURL'));
    //objPage.setRedirect(true);
    //return objPage;
}

}

 

 

 

 

page

 

<apex:page controller="opportunityCustomController">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    </head>
    <style type="text/css">
        <!-- place inline css here from companies table -->
    </style>

    <body>
    <div id="dvMain" style="display:none;">
        <table width="600" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center" >
            <!-- This holds mast for emails. Should be a self enclosed table that floats here. -->
            <tr>
                <td>
                     <table width="100%"  cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF" align="center" >
                        <tr>
                            <td width="50%"  align="left" valign="top" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF">
<a href="http://www.{!Opportunity.WebPartner__c}.com" border="0"><img src="http://www.smartsign.com/companies/logos/{!Opportunity.WebPartner__c}_logo.gif" border = "0" alt="{!Opportunity.WebPartner__c} logo" /></a>
                            </td>
                            <td width="50%" align="right" valign="top" cellspacing="0" cellpadding="0" border="0" bgcolor="#FFFFFF"><a href="http://www.smartsign.com/aboutus.aspx" border="0"><img src="http://www.smartsign.com/companies/logos/a_smartsign_store.gif" border = "0" alt="Learn more about SmartSign" /></a>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
              <td>
                    <c:ShippingUpdate id="ShippingUpdate" rendered="{!IF(emailtype=="/shippingupdate", true, false)}"/>         
                    <c:TrackingInfo id="TrackingInfo" rendered="{!IF(emailtype=="/trackinginfo", true, false)}"/> 
                    <c:forgotpassword id="ForgotPassword" rendered="{!IF(emailtype=="/forgotpassword", true, false)}"/> 
                    <c:OrderConfirmation id="OrderConfirmation" rendered="{!IF(emailtype=="/orderconfirmation", true, false)}"/>   
                </td>
            </tr>
            <!-- This holds footer for emails. Should be a self enclosed table that floats here. -->
            <tr>
                <td>
                   <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr> 
                <td valign="middle" align="left">
                    <IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/xp/policies.asp" title="Policies">Policies</a>
                    &nbsp;&nbsp;<IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/Asset-Tags-FAQ.aspx" title="Frequently Asked Questions">FAQs</a>
                    &nbsp;&nbsp;<IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/material_specs.aspx" title="Material Specifications">Material Specs</a>
                    &nbsp;&nbsp;<IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/aboutus.aspx" title="About Us">About Us</a>
                    &nbsp;&nbsp;<IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/Asset-Tags-Testimonials.aspx" title="Testimonials">Testimonials</a>
                    &nbsp;&nbsp;<IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/xp/ContactUs.aspx" title="Contact Us">Contact Us</a>
                    &nbsp;&nbsp;<IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/xp/disclaimer.asp" title="Disclaimer">Disclaimer</a>
                    &nbsp;&nbsp;<IMG src="http://www.smartsign.com/companies/{!Opportunity.WebPartner__c}/arrow_orange.gif" width="4" height="6" alt=""/> <a href="http://www.{!Opportunity.WebPartner__c}.com/site-map.aspx" title="My Asset Tag Site Map">Site Map</a></td>
                <td align="right">&copy; 2011, {!Opportunity.WebPartner__c}.com</td>
            </tr>
        </table>
                </td>
            </tr>
        </table>
    </div>    
    <apex:form id="frmTxtArea">
        <table width="100%" border="0" cellspacing="3" cellpadding="3" style="padding-top:25px;"> 
            <tr>
                <td>
                    <b> Subject</b> <br />
                    <apex:inputText value="{!subject}" id="Subject" maxlength="80"/><br /><br />
                    <apex:selectList id="ddlBody" value="{!subject}" multiselect="false" size="1" onchange="getBodyValue()">
                        <apex:selectOptions value="{!Items}"></apex:selectOptions>
                    </apex:selectList><br />
                </td>
            </tr>                   
           <tr>               
               <td>
                   <b>Message Body </b> <br />
                   <apex:inputTextarea id="txtAreaBody" value="{!messageBody}" richText="true" rows="30" cols="20"/>
               </td>
           </tr>
           <tr>
               <td>
                   <apex:commandButton value="Send Email" action="{!send}" immediate="{!IF (autosend=="1",true,false)}" />
               </td>
           </tr>
       </table>
   </apex:form>
    </body>
    <script>
        var comp = document.getElementById("dvMain");
        var txtAreaBody = document.getElementById("{!$Component.frmTxtArea:txtAreaBody}");
        txtAreaBody.value = comp.innerHTML;
        
        function getBodyValue()
        {
            var sSubject = ("&body=" + "{!subject}");//alert("sSubject" + sSubject);
            var sValue = document.getElementById("{!$Component.frmTxtArea:ddlBody}");
            var sSelectedValue = sValue.options[sValue.selectedIndex].value;
            //alert("sSelectedValue " + sSelectedValue);
            var cLocation = window.location.href;
            var nSubject = ("&body=" + sSelectedValue); //alert("nSubject" + nSubject);
            var nLocation = cLocation.replace(sSubject, nSubject);//alert("cLocation " + cLocation);
            //alert("nLocation " + nLocation );
            window.location = nLocation;
        }
    </script>
</html>
</apex:page>

 

spraetzspraetz

Getting a page content is not available in trigger context.

 

You can invoke a @future method from a trigger and do it there, though.

ElcalvoMikeElcalvoMike

Only issue I see is that you cannot call getContent method from a future annotation.

I guess i could pass the url on different class.method and handle the getContent method there?