NoClassDefFoundError When trying to use Gmail API to send a email - java

This is my first time using the Gmail REST API and I'm trying to send an email using it. I followed the instructions on Google Developer site and got the authentication part successful. But now when I'm trying to send a email an Exception is thrown. Complete exception is,
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
at javax.mail.Session.initLogger(Session.java:227)
at javax.mail.Session.<init>(Session.java:212)
at javax.mail.Session.getDefaultInstance(Session.java:315)
at gmailconsole.Email.createEmail(Email.java:45)
at gmailconsole.GmailApiQuickStart.main(GmailApiQuickStart.java:91)
Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 5 more
The code that associated with the exception
public static void sendMessage(Gmail service, String userId, MimeMessage email)
throws MessagingException, IOException {
Message message = createMessageWithEmail(email);
message = service.users().messages().send(userId, message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
}
Method call in the main class
try {
MimeMessage mimeMessage = Email.createEmail("isurub1992#gmail.com", "me", "Test", "This is a test message");
Email.sendMessage(service, "me", mimeMessage);
} catch (MessagingException ex) {
ex.printStackTrace();
}
P.S : I have added all the libraries and JavaEE API Library in NetBeasns

ClassNotFoundException is definite: the class is not found in classpath.
Short search reveals that the missing class com.sun.mail.util.MailLogger is found in com.sun.mail_1.4.2.jar; so have a look, I would place a bet that this would solve your problem.
Not the same problem, but it could be a nice information for you, too:
java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

Related

How do I send emails through Outlook using R?

I'm trying to send myself an email through R, and I have an Outlook account (my email address ends in #hotmail.com).
library(mailR)
PASS <- as.character("XXXXXXXXXX")
sender <- "amalik34#hotmail.com"
recipients <- c("amalik34#hotmail.com")
send.mail(from = sender,
to = recipients,
subject="Subject of the email",
body = "Body of the email",
smtp = list(host.name = "smtp-mail.outlook.com", port = 25, user.name="amalik34", passwd=PASS, ssl=TRUE),
authenticate = TRUE,
send = TRUE)
Which returns this error:
java.lang.NoClassDefFoundError: javax/activation/DataHandler at
org.apache.commons.mail.Email.createMimeMessage(Email.java:1832) at
org.apache.commons.mail.Email.buildMimeMessage(Email.java:1268) at
org.apache.commons.mail.Email.send(Email.java:1436) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567) at
RJavaTools.invokeMethod(RJavaTools.java:386) Caused by:
java.lang.ClassNotFoundException at
RJavaClassLoader.findClass(RJavaClassLoader.java:397) at
java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:586) at
java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519) ... 8
more NULL Error: NoClassDefFoundError (Java):
javax/activation/DataHandler
I have no idea what's causing this error or what I'm doing wrong. I see gmail users doing pretty much the exact same steps I'm trying and they don't have any problems.

How to instrument Java application code metrics to Prometheus

I am trying to export customized values metrics of my Java application to Prometheus. I have read that it could be done with Push Gateway, following an example I use the next method:
static void executeBatchJob() throws Exception {
CollectorRegistry registry = new CollectorRegistry();
Gauge duration = Gauge.build()
.name("my_batch_job_duration_seconds").help("Duration of my batch job in seconds.").register(registry);
Gauge.Timer durationTimer = duration.startTimer();
try {
// Your code here.
myCode();
// This is only added to the registry after success,
// so that a previous success in the Pushgateway isn't overwritten on failure.
Gauge lastSuccess = Gauge.build()
.name("my_batch_job_last_success").help("Last time my batch job succeeded, in unixtime.").register(registry);
lastSuccess.setToCurrentTime();
} finally {
durationTimer.setDuration();
PushGateway pg = new PushGateway("172.16.124.40:9091");
pg.pushAdd(registry, "my_batch_job");
}
}
But when I run the project I am having the next error:
Exception in thread "main" java.lang.NoClassDefFoundError: io/prometheus/client/exporter/common/TextFormat
at io.prometheus.client.exporter.PushGateway.doRequest(PushGateway.java:299)
at io.prometheus.client.exporter.PushGateway.pushAdd(PushGateway.java:158)
at nemshelloworld.NemsHelloWorld.executeBatchJob2(NemsHelloWorld.java:78)
at nemshelloworld.NemsHelloWorld.main(NemsHelloWorld.java:33)
Caused by: java.lang.ClassNotFoundException: io.prometheus.client.exporter.common.TextFormat
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
You're missing the simpleclient_common module, which is a listed dependency of simpleclient_pushgateway so it sounds like your pom.xml or equivalent isn't right.

Avoiding NoClassDefFoundError when using JavaMail [duplicate]

This question already has answers here:
Replacements for deprecated JPMS modules with Java EE APIs
(11 answers)
Closed 4 years ago.
I keep getting the NoClassDefFoundError error. I am trying to send an email using the JavaMail API, but the error occurs when I'm creating an instance of Message using the SMTPMessage class.
I know I need the activation library, but it still doesn't work.
By the way, I'm using JDK 10.
The error happens on the first line of this code.
#Override
public void sendEmail(Mail mail) throws MessagingException
{
Message message = new SMTPMessage(this.session);
message.setSubject(mail.getHeader());
message.setFrom(mail.getFrom());
message.setSentDate(mail.getDateClone());
if (mail.getSignature() != null)
message.setText(mail.getText() + "\n\n" + mail.getSignature());
else
message.setText(mail.getText());
Transport.send(message);
}
Stacktrace
Exception in thread "main" java.lang.NoClassDefFoundError: javax/activation/DataSource
at martin.mail.EmailHandler.sendEmail(EmailHandler.java:79)
at martin.Main.main(Main.java:22)
Caused by: java.lang.ClassNotFoundException: javax.activation.DataSource
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 2 more
Solution
Just add the activation library to your own class path. You can put it in your own package.

Spring Boot email sending throws SocketTimeoutException: Read timed out

I've already researched the topic for a few days but none of the answers I found online did the trick for me.
Context: I've got a Spring Boot web application which sends automatic emails notifications using Java Mail API and Spring Boot Starter Mail.
It is using GMail SMTP server with a GSuite account. I recently upgraded to use Spring 5.0.6 and Spring Boot 2.0.2 and the email sending stopped working.
A few clues:
the Java code sending the email is the same as before
Gmail SMTP still works correctly (from another VM using older version of the application with the same settings and authentication, the emails are sent properly).
unless I am missing something, the application configuration remains the same as before
The things that have changed:
upgrade to Spring 5.0.6
upgrade to Spring Boot 2.0.2
changes in many places in the Java code to match this upgrades and add features in other parts of the app
The IP address of the VM is different than before (AWS EC2 instance)
Here are the relevant dependencies in pom.xml :
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Here is the application.yml relevant to Spring mail:
spring:
mail:
host: ${FT_MAIL_SMTP_HOST}
port: ${FT_MAIL_SMTP_PORT}
username: ${FT_MAIL_SMTP_USERNAME}
password: ${FT_MAIL_SMTP_PASSWORD}
debug: false
properties:
mail:
smtp:
starttls:
enable: ${FT_MAIL_SMTP_STARTTLS}
required: ${FT_MAIL_SMTP_TLSREQUIRED}
auth: ${FT_MAIL_SMTP_AUTH}
connectiontimeout: ${FT_MAIL_SMTP_CONN_TIMEOUT}
timeout: ${FT_MAIL_SMTP_TIMEOUT}
writetimeout: ${FT_MAIL_SMTP_WRITE_TIMEOUT}
These variables are defined in the environment:
FT_MAIL_SMTP_HOST=smtp.gmail.com
FT_MAIL_SMTP_PORT=587
FT_MAIL_SMTP_USERNAME=myaccount#myapp.com
FT_MAIL_SMTP_PASSWORD=mypassword
FT_MAIL_SMTP_STARTTLS=true
FT_MAIL_SMTP_TLSREQUIRED=true
FT_MAIL_SMTP_AUTH=true
FT_MAIL_SMTP_CONN_TIMEOUT=5000
FT_MAIL_SMTP_TIMEOUT=5000
FT_MAIL_SMTP_WRITE_TIMEOUT=5000
Here is the Spring #Service used to send the email (unchanged):
#Service
public class EmailServiceImpl {
#Autowired
public JavaMailSender emailSender;
#Autowired
private SpringTemplateEngine templateEngine;
#Value("${myapp.mail.from}")
private String fromAddress;
#Value("${myapp.mail.replyto}")
private String replyToAddress;
public void sendTemplatedMessage(String template, String to, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, fromAddress, replyToAddress, subject, model);
}
public void sendTemplatedMessage(String template, String to, String from, String subject, Map<String, Object> model) throws MailException, MessagingException {
sendTemplatedMessage(template, to, from, replyToAddress, subject, model);
}
private void sendTemplatedMessage(String template, String to, String from, String replyTo, String subject, Map<String, Object> model) throws MailException, MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
//helper.addAttachment("logo.png", new ClassPathResource("memorynotfound-logo.png"));
Context context = new Context();
context.setVariables(model);
String html = templateEngine.process(template, context);
helper.setTo(to);
helper.setFrom(from);
helper.setReplyTo(from);
helper.setSubject(subject);
helper.setText(html, true);
emailSender.send(message);
}
public void sendSimpleMessage(String to, String from, String subject, String text) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setFrom(from);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now here is the error I get when trying to send an email:
04:42:19.900 [https-jsse-nio-443-exec-3] ERROR c.f.controller.StayController - Could not send Guest confirmation email to gfgorostidi#protonmail.com
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
org.springframework.mail.MailSendException: Failed to close server connection after message sending; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:482)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:61)
at com.myapp.util.EmailServiceImpl.sendTemplatedMessage(EmailServiceImpl.java:35)
at com.myapp.controller.StayController.sendConfirmEmailToGuest(StayController.java:437)
at com.myapp.controller.StayController.saveStay(StayController.java:383)
at com.myapp.controller.StayController.createStay(StayController.java:163)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
......
......
......
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2202)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1212)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:473)
... 104 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:65)
at java.base/sun.security.ssl.SSLSocketImpl.bytesInCompletePacket(SSLSocketImpl.java:918)
at java.base/sun.security.ssl.AppInputStream.read(AppInputStream.java:144)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:124)
at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:271)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2182)
... 106 more
I have tried setting an incorrect SMTP server or bad credentials and this made the connection fail, so I assumed the server and credentials are correct as they are, and the error happens after a successful connection.
The account used hasn't reached its limit, as another VM uses the same credentials and sends emails without problem.
I've tried changing "Start TLS" settings to false and use port 465 instead, but this isn't working either.
Any help is appreciated !! Thanks in advance!
After much more trial and error with the configuration, I found out that it required an application property "spring.mail.protocol" in the configuration.
I've added the line protocol: smtp in application.yml:
spring:
mail:
protocol: smtp
And that fixed the read timeout issue, email are now sent properly. Hope that may help someone in the future.
I did face the same issue, but my scenario was a bit different
I was trying to send in a schedule manner using quartz
When I did not use Quartz, it was all working fine, but with quartz it started failing
The above solution did not help me, but pointed me in direction of looking at the properties that I had set.
Increasing the connection timeout did the job for me
Thus changed the application properties
from:
spring.mail.properties.mail.smtp.timeout=3000
to:
spring.mail.properties.mail.smtp.timeout=25000
Hope it works for others as well

Multiple Jar file not found issues with IBM watson personality Insights

I'm writing a watson program to fetch personality traits. However, I'm running into errors with jar file issues.
import com.ibm.watson.developer_cloud.personality_insights.v3.PersonalityInsights;
import com.ibm.watson.developer_cloud.personality_insights.v3.model.Profile;
public JSONArray getPersonalityTraitsFromWatson(String text) {
JSONArray retval = null;
PersonalityInsights service = new PersonalityInsights("2016-10-20", "xxxx", "yyyy");
Profile response = service.getProfile(text).execute();
System.out.println("profile: " + response);
return retval;
}
The first problem is with okhttp3. I get a classnotfound error with JavaNetCookieJar. I'm currently using okhttp3 and javanetcookiejar is missing in it. I picked up the okhttp3 from MVNRepository.
Exception in thread "main" java.lang.NoClassDefFoundError: okhttp3/JavaNetCookieJar
at com.ibm.watson.developer_cloud.service.WatsonService.configureHttpClient(WatsonService.java:137)
at com.ibm.watson.developer_cloud.service.WatsonService.<init>(WatsonService.java:117)
at com.ibm.watson.developer_cloud.personality_insights.v3.PersonalityInsights.<init>(PersonalityInsights.java:52)
at com.ibm.watson.developer_cloud.personality_insights.v3.PersonalityInsights.<init>(PersonalityInsights.java:70)
at com.xyz.social.Watson.getPersonalityTraitsFromWatson(Watson.java:20)
at com.xyz.Testing.UnitTester.startUnitTest(UnitTester.java:1720)
at com.xyz.Testing.UnitTester.main(UnitTester.java:1850)
Caused by: java.lang.ClassNotFoundException: okhttp3.JavaNetCookieJar
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
I tried using "org.apache.servicemix.bundles.okhttp-3.2.0_1.jar" with and with the okhttp3.jar which clears the JavaNetCookieJar error but throws an SSLSocketFactory error (given below)
okhttp3.OkHttpClient$Builder.sslSocketFactory(Ljavax/net/ssl/SSLSocketFactory;Ljavax/net/ssl/X509TrustManager;)
Found the problem, the okhttp-urlconnection-3.8.1.jar & logging-interceptor-3.8.1.jar were required to be added. This fixed the problem.

Categories

Resources