This question already has answers here:
How can I solve "java.lang.NoClassDefFoundError"?
(34 answers)
JAVA: MAIL: How can i solve ClassNotFoundException : javax.mail.internet.AddressException?
(1 answer)
Closed 2 years ago.
I keep getting this same error message every time i try to run my code and im just lost on whats wrong with it. This is my first time trying to write code that will send a email using java via Gmail, here is the error code i keep receiving:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Authenticator
at emailTest.javaMail.main(javaMail.java:5)
Caused by: java.lang.ClassNotFoundException: javax.mail.Authenticator
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more
iv tried looking up for videos online to help me solve the proble, but its really hard since i dont really know what the problem is.
Here is my code:
JavaMailUtil.Java:
package emailTest;
import java.util.Properties;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class JavaMailUtil {
public static void sendMail(String recepient) throws Exception {
System.out.println("preping to send email");
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.sntp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
String myAccountEmail = "removed_for_obvious_reasons;
String myAccountPass = "removed_for_obvious_reasons";
Session session = Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myAccountEmail, myAccountPass);
}
});
Message message = prepareMessage(session, myAccountEmail, recepient);
Transport.send(message);
System.out.println("Message sent succesfully.");
}
private static Message prepareMessage(Session session, String myAccountEmail, String recepient) {
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("myAccountEmail"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
message.setSubject("My first email from java");
message.setText("Hey There, \n Look at my Email");
return message;
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
and here is javaMail.java (contains main method to run):
package emailTest;
public class javaMail {
public static void main(String[] args) throws Exception {
JavaMailUtil.sendMail("removed_for_obvious_reasons_acc2");
}
}
im 100% sure im typing in the senders email and password correct too.
Try using this:
public static void main(String[] args) {
String contentText = "";
String mailWrapper = "";
// Recipient's email ID needs to be mentioned.
final String to = "some#gmail.com";
// Sender's email ID needs to be mentioned
final String from = "to#gmail.com";
String password = "pasword";
// Assuming you are sending email from through gmails smtp
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.debug", "false");
// Get the Session object.// and pass username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
// Used to debug SMTP issues
session.setDebug(false);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Your Subject goes here");
// Now set the actual message
message.setText("This is actual message");
System.out.println("SENDING MAIL...");
// Send message
Transport.send(message);
System.out.println("EMAIL SENT SUCCESSFULLY.");
} catch (MessagingException mex) {
System.out.println("ERROR IN SENDING EMAIL");
}
}
Related
This is the code of the class Mail (there are a main inside but for the simple reason that in this way it seem to be simple to solve this problem):
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class Mail {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "mail";
String psw = "password";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtps.host", host);
properties.setProperty("mail.user", from);
properties.setProperty("mail.password", psw);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
And this is the terminal i see after the running:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/activation/DataSource
at Mail.main(Mail.java:35)
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)
... 1 more
Process finished with exit code 1
The error is on :
MimeMessage message = new MimeMessage(session);
You either need to tell JDK 9 to expose the included-but-hidden java.activation module, or you need to include the JavaBeans Activation Framework (JAF; javax.activation) jar file in your project explicitly.
Do the former by adding --add-modules java.activation to your java command line.
The latter can be done by using this Maven dependency:
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
Try the code below
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 java.util.Properties;
public class MailTest {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "tomail";
// Sender's email ID needs to be mentioned
String from = "frommail";
String psw = "password";
// different mail will have different host name, I have implemented using gmail
String host = "smtp.gmail.com";
String port = "587";
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// props.put("mail.smtp.connectiontimeout", timeout);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
// Get the default Session object.
//Session session = Session.getDefaultInstance(props);
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from, psw);
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
we have an Exchange Server and i wanted to test sending a mail with it. But somehow i always get the error:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Message rejected as spam by Content Filtering.
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Test.sendMailJava(Test.java:89)
at Test.main(Test.java:29)
i tried looking at our exchange if anonymous users were allowed and they are, our Printer also send Mails without any authentification.
Here is my Java code, hope someone can help:
import java.net.URI;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.ServerConfig;
import org.simplejavamail.util.ConfigLoader;
public class Test {
public static void main(String[] args) {
//// // TODO Auto-generated method stub
sendMailJava();
}
public static void sendMailJava()
{
String to = "Recipient"
// Sender's email ID needs to be mentioned
String from = "Sender";
// Assuming you are sending email from localhost
String host = "Server Ip-Adress";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.imap.auth.plain.disable","true");
properties.setProperty("mail.debug", "true");
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Subject");
// Now set the actual message
message.setContent("Content", "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I also tried SimpleMail, but there is the same error.
The Connection to the smtp Server seems to work, but the message cannot be send, cause of the error above. What could it be?
Greetings,
Kevin
Edit:
i found my error, i don't know why our printers can send maisl without errors but it seems i had to whitelist my ip at our exchange server. Code was completely fine.
thanks for the help
I know you are wanting the smtp option, but I have a feeling the issue is how your server is setup and not in your code. If you get the EWS-Java Api, you can log into your exchange server directly and grab mail that way. Below is the code that would make that work:
public class ExchangeConnection {
private final ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // change to whatever server you are running, though 2010_SP2 is the most recent version the Api supports
public ExchangeConnection(String username, String password) {
try {
service.setCredentials(new WebCredentials(username, password));
service.setUrl(new URI("https://(your webmail address)/ews/exchange.asmx"));
}
catch (Exception e) { e.printStackTrace(); }
}
public boolean sendEmail(String subject, String message, List<String> recipients, List<String> filesNames) {
try {
EmailMessage email = new EmailMessage(service);
email.setSubject(subject);
email.setBody(new MessageBody(message));
for (String fileName : fileNames) email.getAttachments().addFileAttachment(fileName);
for (String recipient : recipients) email.getToRecipients().add(recipient);
email.sendAndSaveCopy();
return true;
}
catch (Exception e) { e.printStackTrace(); return false; }
}
}
In your code you just have to create the class, then use the sendEmail method to send emails to whomever.
Your JavaMail code is not authenticating to your server, which may be why the server is rejecting the message with that error message. (Spammers often use open email servers.)
Change your code to call the Transport.send method that accepts a user name and password.
This piece of code is picked up from http://www.tutorialspoint.com/javamail_api/javamail_api_sending_simple_email.htm
//package com.tutorialspoint;
import java.util.Properties;
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 SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "ABC#gmail.com";
// Sender's email ID needs to be mentioned
String from = "PQR#gmail.com";
final String username = "NAME";
final String password = "****";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I tried getting hint from this link. But it seems to be using a slightly different method.
On running it with a debugger, exception seems to be coming from following code:
Transport.send(message);
Following is the stack trace:
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:58)
PS: I have checked the username and password. Also, 2 step sign in process is not enabled for the account from which I am trying to send mail.
Can someone please explain what could be the cause of authenticatio failure? Alternatively, if there is some other post which has already answered the query, please point me to it. Thanks.
The server isn't happy with the username or password you're using. You can probably guess the common reasons that might be the case, staring with you provided the wrong username or password.
The JavaMail Session debugging output might provide more information.
change String host = "relay.jangosmtp.net";
to String host = "smtp.gmail.com";
and Port from 25 to 587
I want to send a mail using Gmail's SMTP server. Can you tell me why it won't connect to server when I run the bellow code.
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class SendTrick {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "465");
props.put("mail.from", "example#gmail.com");
props.put("mail.smtp.host", "smtp.gmail.com");
Session session = Session.getInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
"ex#gmail.com");
msg.setSubject("JavaMail hello world example");
msg.setText("Hello, world!\n");
Transport.send(msg);
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}
The exception in the log is
send failed, exception: javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 25; nested exception is:
java.net.ConnectException: Connection refused: connect
You are not setting a mail.smtp.port since there is a duplication typo on the property mail.smtp.host, therefore the default port 25 is being used, as detailed in the the Exception.
GMail's SMTP is not running on port 25, which is why the connection is being refused. From Set up POP in mail clients, it looks like it should be 465 or 587, so you have a valid value but the property key is incorrect.
Edit:
You need use the correct property key for the port:
props.put("mail.smtp.port", "465"); // <-- use the word "port", not "host"
After this is fixed, you may also find authentication issues, as already noted in the comments, unless you have purposely left out the javax.mail.Authenticator code in the question.
Edit 2:
As I mentioned, you might need to specify additional properties to successfully authenticate and be authorised with the SMTP server, for example:
props.put("mail.smtp.starttls.enable", "true");
But, since you are using port 465 for SSL connection you will also need to specify additional SSL properties such as the mail.smtp.socketFactory.class.
Follow this steps:
Disable "Two factor authentication" in Your Email
Navigate to: "https://myaccount.google.com/lesssecureapps?pli=1" and turn on "Access for less secure apps"
Download JavaMail API "https://www.oracle.com/technetwork/java/javamail/index-138643.html" and Add it to your library
CODE
import java.util.Properties;
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;
public class email_try {
public static void main(String ap[]) {
String myEmail = "YOUR EMAIL";
String password = "YOUR PASSWORD";
String opponentEmail = "THEIR EMAIL";
Properties pro = new Properties();
pro.put("mail.smtp.host", "smtp.gmail.com");
pro.put("mail.smtp.starttls.enable", "true");
pro.put("mail.smtp.auth", "true");
pro.put("mail.smtp.port", "587");
Session ss = Session.getInstance(pro, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myEmail, password);
}
});
try {
Message msg = new MimeMessage(ss);
msg.setFrom(new InternetAddress(myEmail));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(opponentEmail));
msg.setSubject("Your Wish");
msg.setText("java email app");
Transport trans = ss.getTransport("smtp");
Transport.send(msg);
System.out.println("message sent");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
TRY THIS CODE AND PUT CORRECT EMAIL ID AND PASSWORD
public class MailEx {
public static void main(String[] args) {
try {
String userName = "abc#gmail.com";
String password = "123";
String hostName = "smtp.gmail.com";
String fromName = "Splendore Bkk";
String to[] = {"xyz#gmail.com"};
System.out.println("to.length::"+to.length);
Properties props = new Properties();
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
System.out.println("to.length:sadfsadfds:"+to.length);
// Get the default Session object.
Session session = Session.getInstance(props);
// Create a default MimeMessage object.
MimeMessage message1 = new MimeMessage(session);
// Set the RFC 822 "From" header field using the
// value of the InternetAddress.getLocalAddress method.
message1.setFrom(new InternetAddress(userName,fromName));
Address[] addresses = new Address[to.length];
for (int i = 0; i < to.length; i++) {
Address address = new InternetAddress(to[i]);
addresses[i] = address;
// Add the given addresses to the specified recipient type.
message1.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
}
// Set the "Subject" header field.
message1.setSubject("Testing");
// Sets the given String as this part's content,
// with a MIME type of "text/plain".
Multipart mp = new MimeMultipart("alternative");
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent("Hii from cc", "text/html");
mp.addBodyPart(mbp);
message1.setContent(mp);
message1.saveChanges();
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(hostName,userName,password);
transport.sendMessage(message1,addresses);
transport.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
I getting the Error ....
DEBUG: JavaMail version 1.4ea
DEBUG: java.io.FileNotFoundException: ..\Java\jdk1.6.0\jre\lib\javamail.providers (The system cannot find the file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
at javax.mail.Session.loadProvidersFromStream(Session.java:928)
at javax.mail.Session.access$000(Session.java:174)
at javax.mail.Session$1.load(Session.java:870)
at javax.mail.Session.loadResource(Session.java:1084)
at javax.mail.Session.loadProviders(Session.java:889)
at javax.mail.Session.<init>(Session.java:210)
at javax.mail.Session.getInstance(Session.java:249)
at com.test.MailEx.main(MailEx.java:41)
So can u tell me what's the problem...
To avoid DEBUG warnings, create files javamail.providers, javamail.address.map, javamail.default.address.map, javamail.default.providers under
(Program Files)\Java\jdk1.6.0\jre\lib\
folder.
About the error, NoClassDefFoundError, well you simply didn't add JavaMail to your classpath. If you are using Eclipse, right click project, follow Build Path ≥ Add Libraries or something like that and add javamail's jar file (which you should locate under your lib/ folder) to classpath of your project.
I fix it , look how my code is writing
must to approve before in your google account
Set Allow less secure apps to ON
example how i did it https://stackoverflow.com/a/64023055/2347210
Use javax.mail version 1.4.7
import java.util.Properties;
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 void SendEmail() throws Exception {
String EmailUsername = "MYMAIL#gmail.com";
String PasswordUsername = "SomePassword";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EmailUsername, PasswordUsername);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(EmailUsername));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("Example#gmail.com"));
message.setSubject("This is the Qa test!");
message.setText("this is the report");
Transport.send(message);
System.out.println("Message Sent!");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
See this this have solution
my ans check it out
this is having desired solution for your problem
Hope that will help.