+ Start a Discussion
Anto HotelbedsAnto Hotelbeds 

How to send email with attachments in salesforce?



I need to send an attachment  via email through apex.


What I do in my code is create a case, then request for the attachment and once the attachment is introduces I send the email. This attachment can be in multiple formats (xls, txt,...).


I am able to send the attachment, but not in the correct format...Can you tell me please what I am doing wrong?


public PageReference uploadAndSendEmail() {
    //Upload the file
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = case1.Id; // the record the file is attached to
    attachment.IsPrivate = false;
   //I get the intranet Id of the user
    User u=[SELECT Id,Intranet_ID__c FROM User WHERE Id=:case2.OwnerId];
    string interfaceId=u.Intranet_ID__c;
    if (attachment.Body!=NULL){
    	try {
      		//Introduce the attachment
      		insert attachment;
      		//and create and send email
        	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        	String[] toAddresses = new String[] {'a.***@****.com'};
        	Messaging.EmailFileAttachment[] fileAttachments = new Messaging.EmailFileAttachment[1];
  	        Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
      		fileAttachments[0] = fileAttachment;
        	mail.setSubject('New Request: ' + Case2.Subject + ' - ' + Case2.Id + ' - PROJ=32 -     ISSUE='+Case2.Footprints_ID__c);// New Request: {!Case.RecordType} - {!Case.Id} - PROJ=32 - ISSUE={!Case.Footprints_ID__c}
        	mail.setPlainTextBody('Sender= '+string.valueOf(u.Intranet_ID__c)+'\n'+
        							'New Category='+Case2.Footprints_Category__c+'\n'+
        							'Atlas Code: '+ Case2.Atlas_Code__c+'\n'+
        							'Ebilling Email: '+ Case2.E_billing_Email__c+'\n'+
        							'Ebilling Frequency: '+ Case2.E_billing_Frequency__c+'\n'+
        							'Comments: '+ Case2.Comments_for_Admin__c);
        	Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    	} catch (DMLException e) {
      		ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
      		return null;
    	} finally {
      		attachment = new Attachment(); 
//DOESNT MATTER. Sends a different email
    //Fin attachments


Any help is appreciated.