Send Remote Content as a mail attachment in Salesforce


Hi All,

Recently I encountered a situation where I need to fetch some content present in a remote server and need to send this content to salesforce users as attachment in mail.  Without much thinking I started Googling but I didn’t find any soution for this. Finally I came up with my own solution. I am going to give the sample code which may help you if you run into simular situation. Beware that this is just a example code.

First of all I write a controller which handles following tasks: Fetch remote content based on given url and then send an email to the given email address. The code is given below to perform the above mentioned tasks.

public with sharing class GetRemoteContent
{
	public String remoteContentURL {get;set;}
	public String destinationMailAdresses {get;set;}
	public String attachementName{get;set;}
	public String statusMsg{get;set;}

	public String getRemoteContent()
	{
		try
		{
			validateInput(remoteContentURL,destinationMailAdresses,attachementName);
			if(Apexpages.hasMessages(ApexPages.severity.ERROR))
			{
				return null;
			}
			Http http=new Http();
			Httprequest request=new Httprequest();
			request.setEndpoint(remoteContentURL);
			request.setMethod('GET');
			//set timeout to 2 mins.
			request.setTimeout(120000);
			Httpresponse response= http.send(request);
			Blob remoteContentAsBlob=response.getBodyAsBlob();
			GetRemoteContent.sendEmail(destinationMailAdresses.split(';'), attachementName,  remoteContentAsBlob);
			statusMsg='Mail sent successfully..';
			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.INFO,'Mail sent successfully to the following reciepients: '+destinationMailAdresses));
		}
		catch(Exception e)
		{
			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Failed to send Mail. And the reason is:: '+e.getMessage()));
			statusMsg='Failed to send Mail. And the reason is:: '+e.getMessage();
		}
		finally
		{
			if(!Apexpages.hasMessages(ApexPages.severity.ERROR))
			{
				remoteContentURL='';
				destinationMailAdresses=null;
		        attachementName='';
			}
		}
		return null;
	}

	private static void sendEmail(String[] toAddresses,String attachementName,Blob imageAsBlob)
	{
		 Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		 Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
         efa.setFileName(attachementName);
         efa.setBody(imageAsBlob);

         // Sets the paramaters of the email
         email.setSubject( 'TestImageAttachment' );
         email.setToAddresses( toAddresses );
         email.setPlainTextBody( 'This is a test mail to test sending image as file attachemet in mail' );
         email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});// Sends the email
         Messaging.SendEmailResult [] r =
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
         System.debug(r);
	}

	private void validateInput(String remoteContentURL,String destinationMailAdresses,String attachementName)
	{
		if(remoteContentURL==null||remoteContentURL.trim().equals(''))
		{
			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Please provide valid URL. Blank is not allowed.'));
		}

		if(destinationMailAdresses==null||destinationMailAdresses.trim().equals(''))
		{
			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Please provide valid Email address. Blank is not allowed.'));
		}

		if(attachementName==null||attachementName.trim().equals(''))
		{
			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Please provide valid attachementName. Blank is not allowed.'));
		}
	}

}

To test the above functionality you can use below page and access it from Salesforce to test it.

<apex:page controller="GetRemoteContent" tabStyle="Account">
	<apex:sectionHeader title="Send Remote content as a mail attachement" />
	<apex:form >
		<apex:pageBlock title="Enter below values">
			<apex:pageMessages ></apex:pageMessages>

			<table>
				<tr>
					<td>Enter Remote content URL:</td>
					<td><apex:inputText label="test" value="{!remoteContentURL}"
						size="50" /></td>
				</tr>
				<tr>
					<td>Enter Destination Email addresses semicolon (;) separated:</td>
					<td><apex:inputText value="{!destinationMailAdresses}"
						size="50" /></td>
				</tr>
				<tr>
					<td>Enter the name of the attachment:</td>
					<td><apex:inputText value="{!attachementName}" size="50" /></td>
				</tr>
				<tr>
					<td><apex:pageBlockButtons location="bottom">
						<apex:commandButton action="{!getRemoteContent}"
							value="Fetch & Email it." />
					</apex:pageBlockButtons></td>
				</tr>
			</table>

		</apex:pageBlock>
	</apex:form>
</apex:page>

If you access the page it will be rendered as shown below.

SendMail from SalesForce

Now you are ready to test it. Enter details in the screen as required and click on “Fetch & Email it.” button. Thats it.
Note: The remote content site must be added in Security-> Remotesite settings. Otherwise you will get an error.

Hope you enjoy this post. Let me know your comments. Thank you!.

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: