[SalesForce] Send email with attachment dynamically.

I want to attach files dynamically with emails..may be computer you can say..Can we do that…I have created a VF page and using apex:inputfile…Can we send email with attachments..Please provide me some sample code.

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 mail.setToAddresses(emailList);           
 String subject='Trend Analysis Report-PI';
 transient Messaging.EmailFileAttachment [] efaList = new  List<Messaging.EmailFileAttachment> () ;
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName(filename );
        efa.setBody(fileBody);
        efa.setContentType(conType);
        efaList.add(efa) ;

        if(efaList != null) {
        mail.setFileAttachments(efaList) ;
        }
        mail.setCharset('UTF-8'); //Use Signatue
        mail.setUseSignature(true);
        // Send the email

                    mail.setSubject(subject);


        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

VF page

<apex:inputFile value="{!filebody}" fileName="{!filename}" contentType="{!conType}">

I am also getting view state error while uploading file….Can some one tell me how to dynamically attach files.

Thanks

Best Answer

You can use setFileAttachments on the Messaging.SingleEmailMessage object:

Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
attachment.setBody(fileBody);
attachment.setContentType(conType);
attachment.setFileName(filename);
attachment.setinline(false);
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
Related Topic