Did not received mail using Java Mail API - java

I want to write a program which can send mail. I created a VM and installed Windows Server 2012 in it and configured it's SMTP Server. Now when I am trying to send email through my program, I am not getting any exception, also I am not receiving the mail. I found that the mail I sent was received by the SMTP server and it was in it's mailroot/Queue Folder. Following is the code.
String to = "shreyaskothari#gmail.com";
String from = "shreyaskothari#gmail.com";
String host = "// VM IP Address";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("First Email from Java");
message.setText("Hello, This is first email from a Java Program");
Transport.send(message);
System.out.println("Message Sent");
}
catch(Exception e){
e.printStackTrace();
}

VM was not connected to Internet. Once VM got connected to Internet, I received the mail.

Related

Getting this error while trying to send mail using smtp server from java! how to solve this

So i am trying to send a pdf through mail using Gmail smtp port 465 but it keeps on throwing this error,
googled it but couldn't solve this.
i don't understand whats wrong? help me on this?
thanks in advance
tried:
1.changing ports
2.tried to correct something on certificates didn't work
error:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Exception reading response;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sample.pdf.PDFMailing.pdfMail(PDFMailing.java:72)
at com.sample.pdf.GeneratePdf.addDataToPdf(GeneratePdf.java:42)
at com.sample.pdf.Report.main(Report.java:47)
PDFMailing.java
public static void pdfMail(String file){
//Sender email-ID and Password.
final String senderEmail="xxxxxx";//Sender Mail ID
final String password="xxxxx";//Sender Mail ID Password.
//setting the Properties.
Properties props=new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
//Authenticating the mailID of the sender.
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(senderEmail, password);
}
};
//Creating and getting the Session Object.
Session session=Session.getInstance(props, auth);
//Setting the From, To, Subject, MessageBody.
try{
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail));//Sender Mail ID
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("harshapirate#gmail.com"));//Receiver Mail ID
message.setSubject("Sample ECO PDF file");
message.setText("This a Sample ECO PDF file.");
MimeBodyPart bodyPart=new MimeBodyPart();
Multipart multipart=new MimeMultipart();
bodyPart.setText("This is multipart Text.");
//Attachments for any file.
MimeBodyPart pdfAttachment=new MimeBodyPart();
pdfAttachment.attachFile(file);
//Attach the Body part to the Multipart.
multipart.addBodyPart(bodyPart);
multipart.addBodyPart(pdfAttachment);
//Associate multipart to the message.
message.setContent(multipart);
System.out.println("Sending mail is in process.......");
//sending the message to-address mail.
Transport.send(message);
System.out.println("Mail has been sent sucessfully.");
}
catch(Exception e){
throw new RuntimeException(e);
}
}
I presume that is Java 8.0.251. Since you have the latest Java 8 release then this should not be happening:
The root certificates in a 8.0.251 keystore should all be current.
The real smtp.google.com should be using well-known root certificates.
The real smtp.google.com would not be presenting the cert chain in the wrong order.
So I think that something is else "getting in the way". Likely explanations include:
Something that is sending outgoing email connections through an SMTP proxy; e.g. a firewall or anti-virus product.
You are running on an application server that has overridden the set of trusted certificates provided by the JDK.
It is also possible that something has subverted your DNS or IP routing and you are talking to a spoofed "smtp.gmail.com" server.
Check the following:
Check if latest JDK is installed (Command: java -version) so that it has latest
certificates and updated CA's.
Check if there are multiple JDKs or JREs installed: If so remove them.
Check if JAVA_HOME is pointing to the latest JDK you installed.
(Command: echo $JAVA_HOME in linux Or echo %JAVA_HOME% in Windows command prompt)
Check if your system date and time are correct.
If above is verified then your Java installation is fine.
Code:
I see a missing property in your code: props.put("mail.smtp.starttls.enable", "true").
Add it and try.
Hope you are able to access Gmail from your browser at least. This confirms that your machine is able to access Gmail servers - Though not an exact test for SMTP, but it is still good to test.
If you are running inside Tomcat, then ensure you have the latest version and hope it has its certificate store not customized or altered in some way.
If everything above is OK, then either you are behind some proxy or you are hacked.
Maybe check for a system property or other way that someone has defined a different trust store e.g. with: -Djavax.net.ssl.trustStore=somefilename.jks
See: https://www.baeldung.com/java-keystore-truststore-difference
But the default truststore should be $JAVA_HOME/jre/lib/security/cacerts (but its contents vary between the Oracle JDK and OpenJDK - this was later fixed, see: https://openjdk.java.net/jeps/319 )
Inspecting/modifying the contents of the store can be done with the command line tool: keytool or a GUI like: https://keystore-explorer.org/
Before you go crazy try starting your application with the following extra System Property for java (-Dsystempropertyname=value):
-Djavax.net.debug=all
Then you will exactly see all details of the used trust store and offered certificates from the server, details of the SSL/TLS handshake and even all data encrypted/decrypted.
For all the information there is on this subject see the JSSE Reference Guide for your Java version, e.g.: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html
The same kind of code, I have written earlier and is in working state. Could you please give a try on using this code below:
Also, check the proper version of Java installed 8+ in your system, with all the Environment variables properly set and required for your project. If any proxy settings exists in your system, try to remove it and then again running the code.
//this will work only for gmail.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import com.[MyProjectRelatedImports].pojo.EmployeeDetails;
public class SendEmail {
public static void sendMail(List<EmployeeDetails> emplDetails) {
Address[] to = new Address[emplDetails.size()];
try {
for (int i = 0; i < to.length; i++) {
to[i] = new InternetAddress(emplDetails.get(i).getEmail());
}
} catch (MessagingException e) {
e.printStackTrace();
}
// Recipient's email ID needs to be mentioned.
String tom = "xyz#gmail.com";// address of recipient
// Sender's email ID needs to be mentioned
String from = "abc#gmail.com"; //address of sender
// Assuming you are sending email from localhost
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", "emailID"); // User name
properties.put("mail.smtp.password", "password"); // password
properties.put("mail.smtp.port", "587");// default mail submission port
properties.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("emailID", "password"); // username will be your email address and password same as your Gmail account.
// And if your account is protected with 2 step verification then you need to generate the app password from the link provided
//https://security.google.com/settings/security/apppasswords
}
});
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(tom));
//Send Email to multiple recipients
message.addRecipients(Message.RecipientType.TO, to);
// Set Subject: header field
message.setSubject("Subject text via Java Class");
// Now set the actual message
message.setText("Message Content should be written here!!! Regards: Pratishtha Sharma ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mEx){
mEx.printStackTrace();}
}
}

error: package sun.net.smtp is not visible

We are moving some old code to java11.We are creating a smtp client. The coe compilation fails when we use java11.
error: package sun.net.smtp is not visible
[javac] sun.net.smtp.SmtpClient SMTP = new sun.net.smtp.SmtpClient(SMTP_SERVER);
[javac] ^
[javac] (package sun.net.smtp is declared in module java.base, which
does not export it)
looks like smtp package support is removed from the java11. Any suggestions will be helpful.
Regards,
Akj
You can use JavaMail API to send email to get this sorted. Go to below link and download the .jar file and add to your project. If not you can add it as a maven dependency.
https://mvnrepository.com/artifact/javax.mail/mail/1.4.7
A sample code to talk to SMTP server and send email as per below.
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abc#abcmail.com"));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("to#abcmail.com"));
message.setSubject("Mail Subject");
String msg = "This is a sample email ";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
Your configurations can be done with a Java Properties object
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.abcmail.com");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "smtp.abcmail.com");
You should use JavaMail, a Java API for sending and receiving emails via SMTP, POP3, and IMAP.
First, have a look at Oracle docs about sending mail in Java here
The sample code below is extracted from the Oracle docs and illustrate how you should send email using the JavaMail API.
Properties props = new Properties();
props.put("mail.smtp.host", "my-mail-server");
Session session = Session.getInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom("me#example.com");
msg.setRecipients(Message.RecipientType.TO,
"you#example.com");
msg.setSubject("JavaMail hello world example");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport.send(msg, "me#example.com", "my-password");
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
Also, note that to send a mail with Java Mail you need a valid SMTP server and an account in that server.

MailConnectException : nested exception: java.net.SocketException: Permission denied: connect

I was trying to send a mail from gmail id to another using this example. Here is my file:
public class SendHTMLEmail
// Recipient's email ID needs to be mentioned.
String to = "harsh.hr99#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", "Admin");
properties.setProperty("mail.password", "admin");
// 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!");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>", "text/html" );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
I am running Tomcat server on localhost:9091 port. I am receiving following error:
screen shot from cmd
how do I solve this?
Well, you set "host = localhost" so your program will try to use a smtp server located at localhost. Problem is: You don't have (and don't want) a smtp server at localhost installed. At least it seems like that.
I think what you want to do is: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
If you trying this example you will need to keep in mind not to publish it because it contains hard-coded gmail credentials.

Cannot send email using Java code on Windows Server 2008 r2?

I have installed SMTP server and IIS Web server on windows 2008 r2 server. I am trying to send a test email using java code through localhost but i am unable to send an email i get the following error not sure what is that i am doing wrong. Apart from installing the SMTP server is there any setting i need to do because i just installed my smtp server and expecting that this code works?
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for marshell#gmail.com
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1118)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at LotusNotes.SendEmail.main(SendEmail.java:30)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for marshell#gmail.com at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1715)
Java Code:
public static void main(String[] args) {
String to = "marshell#gmail.com";
String from = "imrmsmtpmail";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject Line!");
message.setText("Test email!");
Transport.send(message);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
Probably you have to authenticate to send emails to this server.
AFAIK, you aren't providing any user or password in the connection to the server.
I use something like this:
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", true);
properties.setProperty("mail.user", "PUT AN USERNAME HERE");
properties.setProperty("mail.password", "PUT A PASSWORD HERE");
Session session = Session.getDefaultInstance(properties);
And to make sure you have all the parameters working properly before writing the program it is useful to make a telnet to the mail port (25) to make sure you can send an email directly writing the codes into the server.
In the following link you have an example:
http://support.microsoft.com/kb/153119/en
Altough it may sound extremely technical, it worth to try to make sure that the server send emails from your machine with the given parameters: username (or not username at all), destination address, etc.

Sending email with Servlet on GAE

Am writing the code as follow in my application
public void send_email(String email)
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.sendgrid.net");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("my_username","my_password");
}
});
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("from#no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("ramesh#abc.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is method is called in my servlet class.
After that it executed well and give a message as "Done" on console , but i didnt receive any email in Email-inbox.
If i run this same code as java application it works fine and received an email.
But when i run it on Google web server its not working..
And one thing, here i removed both javaee.jar file and mail.jar files from lib, but still it didn't give any error..
Give me any suggestions guys....
But when i run it on Google web server its not working..
"Google web server" in your case means Google AppEngine? If so then you cannot use the full JavaMail API but must use Google's infrastructure.
An app cannot use the JavaMail interface to connect to other mail
services for sending or receiving email messages. SMTP configuration
added to the Transport or Session is ignored.
Be aware you cannot send an email from just any email address. You need to use one that is authorized in your app's domain.
The email address of the sender, the From address. The sender address must be one of the following types:
The address of a registered administrator for the application. You can
add administrators to an application using the Administration Console.
The address of the user for the current request signed in with a
Google Account. You can determine the current user's email address
with the Users API. The user's account must be a Gmail account, or be
on a domain managed by Google Apps.
Any valid email receiving address
for the app (such as xxx#APP-ID.appspotmail.com).
Any valid email
receiving address of a domain account, such as support#example.com.
Domain accounts are accounts outside of the Google domain with email
addresses that do not end in #gmail.com or #APP-ID.appspotmail.com.
https://developers.google.com/appengine/docs/python/mail/sendingmail

Categories

Resources