Using the Mail class

The Mail class is the proxy for the ColdFusion Mail service, which provides the functionality of the cfmail tag. You specify the required cfmail and child tag attributes for the action as Mail tag attributes. The default Mail action on this tag is send.

The following AIR application uses the Mail Service and file upload functionality. It refers to the CFCredentials.mxml file to reference the credentials of the user for authentication.

Following is the CFCredentials.mxml file being used for the example:

<?xml version="1.0" encoding="utf-8"?> 
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" currentState="collapsed" toolTip="Double Click to Collapse/Expand" creationComplete="retrieveCredential()" headerHeight="5" layout="vertical" mouseDown="check Collapse(event )" resizeEffect="Resize"> 
<mx:Script> 
    <![CDATA[ 
    import mx.controls.Alert; 
    import mx.rpc.http.HTTPService 
    import mx.rpc.events.Result Event; 
    import mx.rpc.events.FaultEvent; 
    import flash.data.EncryptedLocalStore; 
    import flash.utils.ByteArray; 
    public var service:HTTPService = new HTTPService(); 
          private function testConnection () :void 
        { 
               var CF_HTTP URL:String; 
               if(cfip.text == null) 
               { 
                 Alert.show("IP Not provided or Invalid IP Address"); 
               } 
               else if(cfprt.text!= "" && cfcnxtrt.text != "") 
               {CF_HTTPURL="http://"+cfip.text+":"+cfprt. text+"/"   +cfcnxtrt.text+"/flex2gateway/"; 
               } 
               else if(cf prt.text == "" && cfcnxtrt.text == "") 
               { 
                  CF_HTTPURL ="http://"+cfip.text+"/flex2gateway/"; 
               } 
               else if(cf prt.text!= "" && cfcnxtrt.text == "") 
               { 
                  CF_HTTPURL="http://"+cf ip.text+":"+cfprt.text+"/flex2gateway/"; 
               } 
                
                  if(cfserviceusername.text == "" && cfservicepassword.text == "") 
                   { 
                    Alert.show("CF Service UserName and Password are not required to test 
                CF server connectivity but they will be required while using the CF 
                   services","Note"); 
                
                   } 
                   
                service.url = CF_HTTPURL; 
                service.method = "POST"; 
                service.addEventListener(ResultEvent.RESULT,httpResult); 
                service.addEventListener(FaultEvent.FAULT,httpFault); 
                   service.send(); 
         
         } 
         
         public function httpResult(event:ResultEvent):void 
        { 
        Alert.show("Connection with ColdFusion server Successful","Connection Status"); 
        } 
         public function httpFault(event:FaultEvent):void 
        { 
        Alert.show("ColdFusion server could not be reached, Make sure credentials are 
        correct and CF server is running","Error"); 
         } 
         private function checkCollapse(event:MouseEvent):void 
        { 
        if( event.clickCount == 2) 
            { 
                currentState = currentState == "collapsed" ? "":"collapsed"; 
            } 
        } 
        private function rememberCredential():void 
        { 
          var data:ByteArray = new ByteArray(); 
        data.writeUTFBytes(cfip.text); 
        En cryptedLocalStore.setItem('IP', data ); 
          var data:ByteArray = new ByteArray(); 
        data.writeUTFBytes(cfprt.text); 
        Encr yptedLocalStore.setItem('PORT', data ); 
          var data:ByteArray = new ByteArray(); 
        data.writeUTFBytes(cfcnxtrt.text); 
        Encrypt edLocalStore.setItem('CONTEXT', data );   
        var data:ByteArray = new ByteArray(); 
        data.writeUTFBytes(cfserviceusername.text); 
        Encr yptedLocalStore.setItem( 'USER', data );   
        var data:ByteArray = new ByteArray(); 
        data.writeUTFBytes(cfservicepassword.text); 
        Encrypted LocalStore.setItem('PASS', data ); 
        } 
        private function retrieveCredential():void 
        { 
        try{ 
        cfip.text = EncryptedLocalStore.getItem('IP').toString(); 
        cfprt.text = EncryptedLocalStore.getItem('PORT').toString(); 
        cfcnxtrt.text = EncryptedLocalStore.getItem('CONTEXT').toString(); 
        cfserviceusername.text = EncryptedLocalStore.getItem('USER').toString(); 
        cfservicepassword.text = EncryptedLocalStore.getItem(' PASS').to String(); 
        } 
        catch(e:Error) 
        { 
        } 
} 
          private function resetCredential():void 
           { 
            EncryptedLocalStore.reset(); 
            cfip.text = ""; 
            cfprt.text = ""; 
            cfcnxtrt.text  = ""; 
            cfserviceusername.text  = ""  ; 
            cfservicepassword.text = ""; 
          }      
         
    ]]> 
</mx:Script> 
<mx:ControlBar> 
    <mx:Label text="CFServer IP"/> 
    <mx: TextInput id="cfip" text="" width="   70"/> 
    <mx:Label text="CFServer Port"/> 
    <mx:TextInput id="cfprt" text="" width="40"/> 
    <mx:Labeltext="CFServer Context Root (if any)"/> 
    <mx:TextInput id="cfcnxtrt" text="" width="70"/>   
    <mx:Label text="CFService UserName"/> 
    <mx:TextInput id= "cfserviceusername" text="" width="70"/>   
    <mx:Label text="CFService Password"/> 
    <mx:TextInput displayAsPassword="true" id="cfservicepassword" text="" width="70"/>     
    <mx:Button id="testconn" label="Test Connection" click="testConnection()"/> 
    <mx:Button id="save" label=" Remember"click="rememberCredential()"/> 
    <mx:Button id="reset" label ="Reset" click = "resetCred e n tial()"/> 
</mx:ControlBar> 
<mx:states> 
    <mx:State name="collapsed"> 
        <mx: SetProperty  name="height" value="10"/> 
    </mx:State> 
</mx:states> 
</mx:Panel>

The AIR application example is as follows:

<?xml version="1.0" encoding="utf-8"?> 
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" 
xmlns:local="com.*" creationComplete="init()" xmlns:cf="coldfusion.service.mxml.*"> 
<mx:Script> 
<![CDATA[ 
import coldfusion.service.events.*; 
import com.CFCredential; 
import mx.collections.ArrayCollection; 
import mx.binding.utils.BindingUtils; 
import mx.rpc.events.FaultEvent; 
import mx.rpc.events.ResultEvent; 
import mx.controls.Alert; 
import flash.events.*; 
import flash.net.FileReference; 
import flash.net.FileReferenceList; 
import flash.net.URLRequest; 
import flash.net.URLVariables; 
import coldfusion.service.Util; 
    public var fileTypes:Array = new Array(); 
    public var imageTypes:FileFilter = new FileFilter("Images (*.jpg; *.jpeg; *.gif; *.png)" ,"*.jpg; *.jpeg; *.gif; *.png"); 
    public var documentTypes:FileFilter = new FileFilter("Documents (*.pdf), (*.doc), (*.rtf), (*.txt)",("*.pdf; *.doc; *.rtf, *.txt")); 
    [Bindable] 
        private var fileslist:ArrayCollection; 
        private var filereflist:FileReferenceList 
        public var fileRef:FileReference = new FileReference(); 
    [Bindable] 
    public var mailPartArray:Array = [{type:"text",content:"Plain text only"}, {type:"html",content:"<B>bold text man!!</B>"}]; 
    public var uploadURL:URLRequest = new URLRequest(); 
    [Bindable] 
    public var attachCollection:Array = new Array(); 
    public var urlcnt:int=0; 
    public function init():void 
    { 
    fileslist = new ArrayCollection(); 
    filereflist = new FileReferenceList; 
    fileRef = new FileReference; 
    uploadURL.url = "http://"+conf.cfServer+":"+conf.cfPort+ Util.UPLOAD_URL; 
    uploadURL.method = "POST";  // this can also be set to "POST" depending on your needs 
            uploadURL.contentType = "multipart/form-data"; 
            fileTypes.push(imageTypes); 
            fileTypes.push(documentTypes); 
        // Add Event Listeners to UI 
        attachbutton.addEventListener(MouseEvent.CLICK, browseFiles); 
        sendbutton.addEventListener(MouseEvent.CLICK,uploadFiles); 
        filereflist.addEventListener(Event.SELECT, selectHandler); 
        //mailtest.send(); 
        } 
 
//Browse for files 
    private function browseFiles(event:Event):void 
        {        
            filereflist.browse(fileTypes); 
        } 
 
//  called after user selects files form the browse dialogue box. 
    private function selectHandler(event:Event):void 
        {var i:int; 
            for (i=0;i < event.currentTarget.fileList.length; i ++) 
            { 
                fileslist.addItem(event.currentTarget.fileList[i]); 
                attachList.text +=  event.currentTarget.fileList[i].name + ",  "; 
            } 
        }  
    private function uploadFiles(event:Event):void 
    { 
        if (fileslist.length > 0) 
        { 
            fileRef = FileReference(fileslist.getItemAt(0)); 
            fileRef.addEventListener(Event.COMPLETE, completeHandler); 
            fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,dataHandler); 
            fileRef.upload(uploadURL); 
        } 
        else if (fileslist.length == 0) 
            { 
                sendmail(); 
            } 
        } 
 
// called after a file has been successfully uploaded | We use this as well to check if there are any files left to upload and how to handle it 
    private function completeHandler(event:Event):void 
        { 
            // Alert.show("File Uploaded successfully"); 
            fileslist.removeItemAt(0); 
            if (fileslist.length > 0) 
            {  
                uploadFiles(null); 
            }  
        } 
//called after file upload is done and Data has been returned from Server  
    private function dataHandler(event:DataEvent):void 
    { 
        attachCollection[urlcnt++] = {"file": 
        Util.extractURLFromUploadResponse(event.data.toString())}; 
        if (fileslist.length == 0) 
            sendmail(); 
    } 
    private function sendmail():void 
    { 
        mailtest.execute(); 
    } 
    public function handleResult(event:ColdFusionServiceResultEvent):void 
    { 
        from.text="";too.text=""; cc.text="";bcc.text=""; 
        subject.text="";mailbody.text=""; 
        attachList.text=""; fileslist.removeAll(); 
        Alert.show("Mail was delivered Successfully"); 
    } 
    public function handleError(event:ColdFusionServiceFaultEvent):void 
    { 
        Alert.show("Failure"+ event.toString()); 
    } 
    ]]> 
</mx:Script> 
<mx:Panel width="100%" height="100%"> 
    <local:CFCredential id="cred" /> 
    <mx:ControlBar> 
    <mx:Spacer width="100%"/> 
    <mx:HBox> 
        <mx:Button label="Send Mail" id="sendbutton"/> 
        <mx:Button label="Attachment" id="attachbutton"/> 
    </mx:HBox> 
    </mx:ControlBar> 
<mx:VBox width="100%" height="100%"> 
    <mx:HBox width="100%"> 
    <mx:Text text="From" width="100" /> 
    <mx:TextInput width="100%" id="from"/> 
    </mx:HBox> 
    <mx:HBox width="100%"> 
    <mx:Text text="To" width="100"/> 
    <mx:TextInput width="100%" id="too"/> 
    </mx:HBox> 
    <mx:HBox width="100%"> 
    <mx:Text text="CC" width="100"/> 
    <mx:TextInput width="100%" id="cc"/> 
    </mx:HBox> 
    <mx:HBox width="100%"> 
    <mx:Text text="Bcc" width="100"/> 
    <mx:TextInput width="100%" id="bcc"/> 
    </mx:HBox > 
    <mx:HBox width="100%"> 
    <mx:Text text="Subject" width="100"/> 
    <mx:TextInput width="100%" id="subject"/> 
    </mx:HBox> 
    <mx:HBox width="100%"> 
    <mx:Text text="Attachments" width="100"/> 
    <mx:TextInput width="100%" id="attachList"  enabled="false" 
    backgroundDisabledColor="white"/> 
    </mx:HBox> 
    <mx:TextArea width="100%" height="100%" id="mailbody"/> 
</mx:VBox> 
</mx:Panel> 
 
    <!--Provide your CF server credentials here--> 
        <cf:Config id="conf" 
        cfServer="{cred.cfip.text}" 
        cfPort="{int(cred.cfprt.text)}" 
        cfContextRoot="{cred.cfcnxtrt.text}" 
        servicePassword="{cred.cfservicepassword.text}" 
        serviceUserName="{cred.cfserviceusername.text}" 
    /> 
 
    <cf:Mail id="mailtest" 
        server="10.192.36.227" 
        to="{too.text}" bcc="{bcc.text}" cc="{cc.text}" 
        failTo="jayesh@adobe.com" replyTo="jayesh@adobe.com" 
        subject="{subject.text}" content="{mailbody.text}" 
        from="{from.text}" 
        attachments="{attachCollection}" 
        type="text" charset="utf-8" mailerId="CF" priority="1" 
        timeout="60" useTLS="true" wrapText="5" 
        result="handleResult(event)" 
        fault="handleError(event)" 
    /> 
</mx:WindowedApplication>