Send Emails Via Eclipse Send Email Example 9.0

The Eclipse Web Tools Project provides excellent tools for working with web services. In this sample we will demonstrate how to send a single email or mass emails in Java using the Eclipse platform. This sample requires that you have Eclipse 3.2 with the Web Tools Project and Apache Axis 1.4 and Apache Tomcat 5.5.20.

For instructions on how to install and configure Eclipse and setup a web tools project, visit this page

To learn how you can send emails via the AJAX Toolkit click here

Contents

Java Example

Java Package name for the project

package com.sforce.EmailApiProject;

Header Files

Import all the files you need to run your project

import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import com.sforce.soap.enterprise.EmailPriority;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.MassEmailMessage;
import com.sforce.soap.enterprise.SendEmailResult;
import com.sforce.soap.enterprise.SessionHeader;
import com.sforce.soap.enterprise.SforceServiceLocator;
import com.sforce.soap.enterprise.SingleEmailMessage;
import com.sforce.soap.enterprise.SoapBindingStub;
import com.sforce.soap.enterprise.fault.InvalidIdFault;
import com.sforce.soap.enterprise.fault.LoginFault;
import com.sforce.soap.enterprise.fault.UnexpectedErrorFault;

Main Class

Public class containing your void main

public class emailAPIExample {

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Running......");
		System.out.println("My ADN Email API Example");
		SoapBindingStub binding;

Authenticate

The SOAP end point is derived from the WSDL you have installed in Eclipse. Add your salesforce.com username and password to authenticate and get a session id, if you the authorization is successful.

		
		try {
			binding = (SoapBindingStub) new SforceServiceLocator().getSoap();
	                LoginResult lr = binding.login("xxxx@xxxx.com", "xxxxxxxx");
			binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY, lr.getServerUrl());
			SessionHeader sh = new SessionHeader();
			sh.setSessionId(lr.getSessionId());
			binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "SessionHeader", sh);
			
			System.out.println(binding.getUserInfo().getUserFullName());

Create the SingleEmailMessage

Initiate an instance of the SingleEmailMessage object that you are going to send in this example.

SendEmailResult will hold the return values from the API call

Email Priority is set to Low - can be set to "Lowest", "Low", "Normal", "High", "Highest"

The charset controls what encoding your email will be send in, if you are using multi-byte characters you should use UTF8 or another multi-byte character set.

Subject will be the subject of your email

You can specify another reply-to address than the from address.

Save as an Activity can be used if you send to an object (User, Lead or Contact) if you send it to an email address you specify, you will not be able to save it as an activity.

HTMLBody can be specified either by typing it in, or you could grab the content from another system/website or application.

TextBody can be specified just as the HTMLBody, but any html codes will be printed as text in the email editor.

  • If you specify both HTML and Text the email will be send as a multipart email
  • If you only specify Text it will be send as Text/plain
  • If you only specify HTML it will be send as Html/plain

TargetObjectID allows you to specify contacts, leads and users you want to send emails too.

ToAddresses allows you to add individual email addresses, like for example rmencke@salesforce.com, you can also specify CC and BCC email addresses as well.


			/* SINGLE EMAIL SAMPLE CODE */
			
			SendEmailResult[] sendEmailResults; 
			

			SingleEmailMessage email = new SingleEmailMessage(); 

		EmailPriority emPrio = EmailPriority.Low;
	        email.setEmailPriority(emPrio);
		email.setCharset("UTF8");
	        email.setSubject("ADN Email API Test Email!"); 
	        email.setReplyTo("r@smus.us");
	        email.setSaveAsActivity(false);       
	     
	        email.setHtmlBody("<font face=arial size=2><img src='http://wiki.apexdevnet.com/skins/adnskin/images/hdr_apexdn.gif' border='0'>" +
	        				  "<p><b>Welcome to ADN Email API Sample</b> <p> With the wsdl you can generate cool emails and send them out <p> " +
	        				  "<i>ApexDeveloper Network<br><a href=http://wiki.apexdevnet.com/>http://wiki.apexdevnet.com/</a><i>");
	        
	        email.setPlainTextBody("Welcome to ADN Email API Sample " +
	        						"\nWith the salesforce.com webservice API's you can generate cool emails and get them send out" +
	        				        "\n\n ApexDeveloper Network \n http://wiki.apexdevnet.com/");

	        email.setTargetObjectId("0033000000Ja2h4");
	        String toAddresses [] = {"rmencke@salesforce.com"};
	        email.setToAddresses(toAddresses);
    

Send the SingleEmailMessage

Submit the SingleEmailMessage and send the email(s) out.

The result of the API call comes back into the sendEmailResults and based on the result printout success or error

	        
	        sendEmailResults = binding.sendEmail(new SingleEmailMessage[] {email});
		    	   
			        System.out.println(sendEmailResults);
		        
			           for (SendEmailResult sendEmailResult : sendEmailResults) { 
			                   if(sendEmailResult.isSuccess()){ 
			                         System.out.println("success"); 
			                   } else{ 
			                         System.out.println("error");
			                   } 
			           } 

Mass Email Message Example

Example of how you can send out a mass email to contacts, leads or users.

First we re-set the sendEmailResults to null, so it doesn't carry over the results from the SingleEmailMessage and create an instance of the MassEmailMessage object.

We specify the MassTargetObjects[] which is an array of contacts, leads or users you can send mass emails to.

We set the templateId we want to leverage for this mass email.

Submit the API request and send the email, after that we printout if it was successful or had an error.

	           
/* MASS EMAILS SAMPLE CODE */			           
			           
 			sendEmailResults = null;			

			MassEmailMessage mEmail = new MassEmailMessage(); 
			mEmail.setEmailPriority(emPrio);

			mEmail.setReplyTo("r@smus.us");
			mEmail.setSaveAsActivity(false);
			String toMassTargetObjects [] = {"0033000000Ja2h4"};
			mEmail.setTargetObjectIds(toMassTargetObjects);
				    
			mEmail.setTemplateId("00X30000000vQ06");
				        			
			sendEmailResults = binding.sendEmail(new MassEmailMessage[] {mEmail});

			System.out.println("Mass Emails - Result - Output from request");
			System.out.println(sendEmailResults);
						        
			for (SendEmailResult sendEmailResult : sendEmailResults) { 
			        if(sendEmailResult.isSuccess()){ 
			                System.out.println("success"); 
			          } else{ 
			                System.out.println("error");
                        }

Exception Handling

Exception handling for any errors being returned.


System.out.println(sendEmailResult.getErrors()[0].getMessage());
				                   } 
					           }        			           
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnexpectedErrorFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidIdFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (LoginFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}