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

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.

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();}
}
}

Cannot send email without authentication required

I wrote a simple Java program that uses Java Mail API to send an email.
public static void main(String[] args) {
System.out.println("SimpleEmail Start");
String smtpHostServer = "smtp.gmail.com";
String emailID = "xxxxxx#hotmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);
EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body");
}
}
EmailUtil class:
public class EmailUtil {
/**
* Utility method to send simple HTML email
* #param session
* #param toEmail
* #param subject
* #param body
*/
public static void sendEmail(Session session, String toEmail, String subject, String body){
try
{
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no_reply#example.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("no_reply#example.com", false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
With this implementation, it is said I do not need any password at all so i gave this a tried and it tells me:
com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required
I got this code from an online resources and from what I read,it should be able to send without authentication.
So my question is, do I always need to set a username and password to send mail using JAVA mail?
If no, what am I doing wrong?
It depends on who's running the server.
See https://support.google.com/a/answer/176600?hl=en&vid=0-974788924023-1554173451081; specifically the column labeled 'Gmail SMTP server' (which you're using). Google explicitly says that you have to authenticate to utilize that server. Not doing so gives you this error message.
Once upon a time you could use any mail server to send emails to any email address you wanted.
And then came SPAM. Spammers also could use any mail server to send emails to any email address - and as a mail server operator you do not want spammers to use your server for sending emails (because operating the server costs you money, because your mail server can get blacklisted for spamming).
So today most mail servers require that you
either provide authentication (for sending emails to any email address you want)
or are only allowed to send emails to email addresses hosted by the mail server operator
Google even has two distinct mail servers:
one that requires authentication, that can be used for sending emails to any email address you want (that is the server at smtp.gmail.com)
one that doesn't require authentication, that can only be used for sending emails to Gmail or G Suite users (that is the server aspmx.l.google.com)
It could be that your source dates back to a time when no authentication was required or that the mail server in your source was only used for sending mails to addresses that are hosted at the mail server.
Either way - if you want to use the server smtp.gmail.com for sending mails to any address you must authenticate (or convince google that they should allow you - and only you - to sending emails without authentication, but then: how will google know that it is exactly you who is trying to send mails?)

external email not working exchange and javamail

Good morning to all,
I was try send external email in my organization does not working for me.When i was try internel email address it working fine.. I am getting exception "invalid mail address 5.1.7 unable to relay"
I am also try send with external email via TELNET. Its working fine in TELNET.
Exchange 2013 receive connector anonymous relay was enable.
Properties props = System.getProperties();
props.put(SMTP_HOST_KEY,smtphost);
Session session=null;
System.out.println("Entering into sendSMTPMail=============(props)"+props);
MailAuthentication authorization =new EmailManager().new MailAuthentication();
LogWriter.log("CREATING THE DEFAULT SESSION");
System.out.println("Entering into sendSMTPMail=============(AUTHORIZATION)"+AUTHORIZATION);
System.out.println("Entering into sendSMTPMail=============(authorization)"+authorization);
System.out.println("Entering into sendSMTPMail=============(session)"+session);
if(AUTHORIZATION)session = Session.getInstance(props, authorization);
else session = Session.getInstance(props, null);
session.setDebug(debug);
System.out.println("Entering into sendSMTPMail=============(session)"+session);
OUTPUT in java :
Send is OK
rcpt is Invaild mail address 5.1.7 unable relay
OUTPUT in TELNET:
Send is OK
rcpt is OK
Help is needed......Please let me know what is problem in javacode or exchange 2013
Thanks.....

Did not received mail using Java Mail API

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.

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.

Categories

Resources