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.
Related
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");
}
}
I have looked at many postings on the ( I need to add the mail.jar and activation.jar to oracle Sql developer ):
"javax.mail.NoSuchProviderException:No provider for Address type: rfc822"...
I have written other classes in java that are used by Oracle Forms6i, but can't get this email portion to work. The code that seems to be failing is:
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 EnvoyerEmail {
private String username = "xxxxxxx#gmail.com";
private String password = "****";
public void envoyer() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xxxxx#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yyyyyy#gmail.com"));
message.setSubject("Test email");
message.setText("Bonjour, ce message est un test ...");
Transport.send(message);
System.out.println("Message_envoye");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
EnvoyerEmail test = new EnvoyerEmail();
test.envoyer();
}
}
But I keep getting the error mentioned above when it tries to send it. I assure you that I have the mail.jar, activation.jar, pop3.jar, mailapi.jar, smtp.jar, imap.jar in the class path. So that is not the problem.
I was suggested on an Oracle Forum that this will need to be signed. I'm very ignorant of this (the java experience that I have is with JSP), but thought that I got things "secured/signed", but I still keep getting the same problem.
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();
}
}
}
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
I am using a program to send emails. The code works when I use some other mail server. but I need to use my company's email account to send email. And the email account is provided by gmail xxxx#companyname.com. When I change the mail host to `stmp.gmail.com, I encounter the following error:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. st6sm11092256pbc.58
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1515)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1054)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:634)
at javax.mail.Transport.send0(Transport.java:189)
at javax.mail.Transport.send(Transport.java:118)
at Mail.sendMail(Mail.java:48)
at Test.main(Test.java:6)
The code is as follows
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Email_Autherticator extends Authenticator {
String username = "xxxx#gmail";
String password = "xxxxx";
public Email_Autherticator() {
super();
}
public Email_Autherticator(String user,String pwd){
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
private String host = "smtp.gmail.com";
private String mail_head_name = "this is head of this mail";
private String mail_head_value = "this is head of this mail";
private String mail_to = "xxxx#gmail.com";
private String mail_from = "xxxx#Comanyname.com";//using gmail server
private String mail_subject = "this is the subject of this test mail";
private String mail_body = "this is mail_body of this test mail";
private String personalName = "xxx";
public void sendMail() throws SendFailedException{
try {
Properties props = new Properties();
Authenticator auth = new Email_Autherticator();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
System.out.println(props);
Session session = Session.getDefaultInstance(props,auth);
MimeMessage message = new MimeMessage(session);
message.setContent("Hello","text/plain");
message.setSubject(mail_subject);
message.setText(mail_body);
message.setHeader(mail_head_name, mail_head_value);
message.setSentDate(new Date());
Address address = new InternetAddress(mail_from,personalName);
message.setFrom(address);
Address toaddress = new InternetAddress(mail_to);
message.addRecipient(Message.RecipientType.TO,toaddress);
System.out.println(message);
Transport.send(message);
System.out.println("Send Mail Ok!");
} catch (Exception e) {
e.printStackTrace();
}
//return flag;
}
}
You almost certainly just need to rework your code to add the properties defined in the JavaMail API - Sending email via Gmail SMTP example example.
You can probably get away with setting your props to this:
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.user", gmailUsername);
properties.setProperty("mail.smtp.password", gmailPassword);
As this seems to be for work--if you can--I suggest using Spring. It makes it a lot cleaner and easier to use. I just recently did something similar to this with Spring and Gmail SMTP.
You need to define below properties in your java code.
import below package
import java.util.Properties;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
and add following to your code:
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Use javax.mail.authenticator to authenticate with gmail servers
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Try this should work for you.
If still having issues, refer this error doc:
https://pepipost.com/tutorials/common-javamail-smtp-errors/
for sending SMTP email using javaMail API