Send email with a service task implemented by a java class

Hello all,

I have modeled a simple process with just one service task in order to see how emails can be send with a service task implemented by a java class.

So, I modeled the following:
image

I created a maven project, in which I created a java class with the following code.

package com.camunda.demoEmail.demoEmail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;


public class SendEmail implements JavaDelegate {
	public void execute (DelegateExecution execution) throws Exception{
		
			String email=(String) execution.getVariable("email");
			System.out.println("Prepare an email to "+email);
			Properties properties=new Properties();
			
			properties.put("mail.smtp.auth", "true");
			properties.put("mail.smtp.starttls.enable", "true");
			properties.put("mail.smtp.host", "smtp.gmail.com");
			properties.put("mail.smtp.port", "587");
			
			String myAccountEmail="***********************";   //the gmail account
			String password=" ******************** ";     //the password
			
			Session session=Session.getInstance(properties, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(myAccountEmail,password);
				}
			});
			
			Message message=new MimeMessage(session);
			message.setFrom(new InternetAddress(myAccountEmail));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
			message.setSubject("Uom Bank - Loan Application");
			message.setText("Your application has been created.");
			
			Transport.send(message);
			System.out.println("Message sent successfully");
	
			
	}
}

When I start this process from tasklist, I create a variable email that will be fetched from the java class and it will contain the recipient email.

However, I receive the following error.

Could someone help me on that?
Do I have an error on my java class?

Thank you all in advance.

Are you deploying the model in the WAR file along with your java class?
Also - can you upload your model?

Hi @Niall,

thank you so much for your reply. I attach my simple bpmn model.diagram.bpmn (2.4 KB)

What I have done is to create a maven project, in which I created a java class named “SendEmail”. Then I install the Maven project and paste the “demoEmail.war” file inside the webapps folder of tomcat server.

The code of the java class is exactly the following:

package com.camunda.demoEmail.demoEmail;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;


public class SendEmail implements JavaDelegate {
	public void execute (DelegateExecution execution) throws Exception{
		
			String email= (String) execution.getVariable("email");
			System.out.println("Email preparation to "+email);
			
			Properties properties=new Properties();
			
			properties.put("mail.smtp.auth", "true");
			properties.put("mail.smtp.starttls.enable", "true");
			properties.put("mail.smtp.host", "smtp.gmail.com");
			properties.put("mail.smtp.port", "587");
			properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
			
			String myAccountEmail="**********";
            String password="*************";
			
			Session session=Session.getInstance(properties, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(myAccountEmail,password);
				}
			});
			
			Message message= prepareMessage (session, myAccountEmail, email);
			
			
			try {
				Transport.send(message);
				System.out.println("Message sent successfully");
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("Message was not send");
			}
			
			
	}

	private static Message prepareMessage(Session session, String myAccountEmail, String recipient) {
		try {
			Message message=new MimeMessage(session);
			message.setFrom(new InternetAddress(myAccountEmail));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress (recipient));
			message.setSubject("Uom Bank - Loan Application");
			message.setText("Your application has been created.");
			return message;
			
		} catch (Exception ex) {
			Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE,null, ex);
		}
		return null;
	}
}

When I start my process instance on Tasklist I create a new variable “email” as String type with value a valid email address.

What I have noticed is that if I create a Java Project, with a java class “JavaMailUtil” that has exactly the same code and another java class “JavaMail” that it has a main method, the email is sent successfully. I paste here also the classes for the java project that works without issues.

JavaMailUtil class:

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailUtil {
	public static void sendMail(String recipient) {
		System.out.println("Prepare an email to ");
		Properties properties=new Properties();
		
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.port", "587");
		properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
		
		String myAccountEmail="******************";
		String password="**************";
		
		Session session=Session.getInstance(properties, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(myAccountEmail,password);
			}
		});
		
		Message message= prepareMessage (session, myAccountEmail, recipient);
		
		
		try {
			Transport.send(message);
			System.out.println("Message sent successfully");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Message was not send");
		}
		

	}

	private static Message prepareMessage(Session session, String myAccountEmail, String recipient) {
		try {
			Message message=new MimeMessage(session);
			message.setFrom(new InternetAddress(myAccountEmail));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress (recipient));
			message.setSubject("Uom Bank - Loan Application");
			message.setText("Your application has been created.");
			return message;
			
		} catch (Exception ex) {
			Logger.getLogger(JavaMailUtil.class.getName()).log(Level.SEVERE,null, ex);
		}
		return null;
	}
}

And the “JavaSend” class:

public class JavaMail {
	public static void main(String[] args) throws Exception {
		JavaMailUtil.sendMail("someone@gmail.com");
	}
}

Niall, if you could help me on that I would be so grateful for your assistance and your kindness to help me. I have spent so many hours without understanding what I am missing, since the java project works perfectly, but when I deploy my similar maven project, I face issues.

Thank you in advance. Looking forward to solving this.

I’ll take a look at this - can you put your project on github so that i can run it myself locally and see whats going on?
Also, if you could post the logs of whats happening that would also be handy.

@Niall Hi Niall,

first of all thank you again for your help.

Its the first time that I create a project on github, so I need to apologize if what I did is not what you expected.
github

That’s why I also paste here the logs and the message that I receive on Tasklist.

30-Oct-2020 12:14:42.617 SEVERE [http-nio-8080-exec-2] org.camunda.commons.logging.BaseLogger.logError ENGINE-16004 Exception while closing command context: ENGINE-09008 Exception while instantiating class 'com.camunda.demoEmail.demoEmail.SendEmail': ENGINE-09017 Cannot load class 'com.camunda.demoEmail.demoEmail.SendEmail': javax/mail/MessagingException
        org.camunda.bpm.engine.ProcessEngineException: ENGINE-09008 Exception while instantiating class 'com.camunda.demoEmail.demoEmail.SendEmail': ENGINE-09017 Cannot load class 'com.camunda.demoEmail.demoEmail.SendEmail': javax/mail/MessagingException
                at org.camunda.bpm.engine.impl.util.EngineUtilLogger.exceptionWhileInstantiatingClass(EngineUtilLogger.java:89)
                at org.camunda.bpm.engine.impl.util.ClassDelegateUtil.instantiateDelegate(ClassDelegateUtil.java:54)
                at org.camunda.bpm.engine.impl.bpmn.behavior.ClassDelegateActivityBehavior.getActivityBehaviorInstance(ClassDelegateActivityBehavior.java:112)
                at org.camunda.bpm.engine.impl.bpmn.behavior.ClassDelegateActivityBehavior$1.call(ClassDelegateActivityBehavior.java:68)
                at org.camunda.bpm.engine.impl.bpmn.behavior.ClassDelegateActivityBehavior$1.call(ClassDelegateActivityBehavior.java:65)
                at org.camunda.bpm.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior.executeWithErrorPropagation(AbstractBpmnActivityBehavior.java:90)
                at org.camunda.bpm.engine.impl.bpmn.behavior.ClassDelegateActivityBehavior.execute(ClassDelegateActivityBehavior.java:65)
                at org.camunda.bpm.engine.impl.pvm.runtime.operation.PvmAtomicOperationActivityExecute$2.callback(PvmAtomicOperationActivityExecute.java:61)
                at org.camunda.bpm.engine.impl.pvm.runtime.operation.PvmAtomicOperationActivityExecute$2.callback(PvmAtomicOperationActivityExecute.java:50)
                at org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl.continueIfExecutionDoesNotAffectNextOperation(PvmExecutionImpl.java:2036)
                at org.camunda.bpm.engine.impl.pvm.runtime.operation.PvmAtomicOperationActivityExecute.execute(PvmAtomicOperationActivityExecute.java:42)
                at org.camunda.bpm.engine.impl.pvm.runtime.operation.PvmAtomicOperationActivityExecute.execute(PvmAtomicOperationActivityExecute.java:31)
                at org.camunda.bpm.engine.impl.interceptor.AtomicOperationInvocation.execute(AtomicOperationInvocation.java:99)
                at org.camunda.bpm.engine.impl.interceptor.CommandInvocationContext.invokeNext(CommandInvocationContext.java:131)
                at org.camunda.bpm.engine.impl.interceptor.CommandInvocationContext.performNext(CommandInvocationContext.java:111)
                at org.camunda.bpm.engine.impl.interceptor.CommandInvocationContext.performOperation(CommandInvocationContext.java:86)
                at org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:628)
                at org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity.performOperation(ExecutionEntity.java:602)
             

Also please check that all associated dependencies like javax.mail jar files are included in the war file. If not please copy it into the Camunda distribution jar folder. If it is a maven project , check the scope of these dependencies as well.

Hey @prasadps, thanks for you reply.

Could you please elaborate it, since I am relative “new” to camunda and java world.

I use an apache tomcat server.
1)Where exactly do I need to paste the javax.mail jar file?
2) It is a maven project, but I don’t understand how can I check the scope of the dependencies. If you could explain to me what I have to do, I would be really grateful!

just copy it to the lib folder of your tomcat and give it a shot.

I just copied the jar file in the lib folder of tomcat, and it works!!!
Thank you so so much!!

That was the reason that it didn’t work.

So, one last question… every time that I use a library inside my java class, I need also to paste the jar file in the lib folder of tomcat?? is there another way to do so? (can I include it also in the war file that it will be deployed on the engine? )

The ideal way is to include the jar files inside the war, unless multiple process applications share the same library. Yo can configure your maven to include your dependencies ( usually default scope provides this).

2 Likes

Since you are already using maven, you shouldn’t paste the jar inside the lib folder, you should instead let maven handle dependency management.

In the root folder of your maven project there’s a pom.xml file, where you declare your dependencies.
Just add the following inside the <dependencies> tag:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.4.5</version>
</dependency>
2 Likes