javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful - java

I am sending e email using an SMTP error . I am getting Authentication unsuccessful. The username and password are correct. Am I doing something wrong.
The error logs are
import java.util.Properties;
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;
public class EmailSender{
public static void main(String args[]) {
String to = "ssss#xxx.om"; // sender email
String from = "dddd#xxx.com"; // receiver email
String host = "dkdkdd.xxx.com"; // mail server host
String login="dkkdkd";
String pass="dkkdkd";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.user", login);
properties.setProperty("mail.smtp.password", pass);
properties.setProperty("mail.smtps.ssl.enable", "true");
// properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties); // default session
try {
MimeMessage message = new MimeMessage(session); // email message
message.setFrom(new InternetAddress(from)); // setting header fields
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail from Java Program"); // subject line
// actual mail body
message.setText("You can send mail from Java program by using");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, login, pass);
Transport.send(message);
System.out.println("Email Sent successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
The error is
DEBUG SMTP: AUTH NTLM failed
Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
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)

Had the same issue. It's an MS Exchange error that you receive. You are probably not allowed to use your email to send an email via a relay. The administrator of the Exchange server needs to give the rights to do that.
It has nothing to do with a configuration problem on the Java side.

It looks like the problem in how you do the session part...
try doing this:
private Properties emailPorperties;
...
...
emailPorperties = new Properties();
emailPorperties.put("mail.smtp.host", "your host");
emailPorperties.put("mail.smtp.socketFactory.port", "your port");
emailPorperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
emailPorperties.put("mail.smtp.auth", "true");
emailPorperties.put("mail.smtp.port", "your port");
emailPorperties.put("mail.smtp.ssl.enable", "true");
emailSession = Session.getInstance(emailPorperties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("Authenticating");
return new PasswordAuthentication(USER_NAME, PASSWORD);
}
});

Hello i've got the same issue in the past.
So to solve it i have to connect on the webmail of my outlook or exchage and i noticed that these connexions were stopped by the server so inside i confirm that these transactions was mine.
So u have also to do it usually every 2 month in my case.
The problem is not in the code. The problem occurs because something is wrong with the configuration of the mailboxes I believe.

Same issue resolve by enabling IMAP of the sender email account in Exchange Control Panel (ECP) of outlook mail admin.

Go to your Microsoft admin account and turn off the multi-factor authentication.
By default it is enabled. Once you disable the multi-factor authentication then it works fine for me.

I had a similar issue and in my case, the issue was 'outlook password got expired'.
As I had it logged in default I did not have any issue while logging in to my mail.
I tried logging in to incognito mode and see if my logging asked for an additional layer for logging like multi-factor auth, And when logged in from the incognito tab it asked to change the password with a popup stating 'password got expired'.
I then updated the new password and it started to work fine !!

Related

Not able to send Mail in Java through SMTP server

When I try to send mail in java from my personal email like (sp#gmail.com) it is sent successfully.
But when I am using my company email(sp#example.com) it throws Authentication failed exception. I am using TLS authentication and it is successfully connected to host.
When I am manually login on my email it will always ask for Two Step
verification. Even if I have disabled my two step verification and have also done the change to make it less secure, it still asks for two step verification as it is showing this message after putting my username and password:
2-Step Verification
Based on your organization's policy, you need to turn on 2-step verification. Contact your administrator to learn more.
Enter one of your 8-digit backup codes
In this situation what should I do? As this is my first task in this company, I would be so happy if you could help me. How I can solve this problem?
My code :
String to = "abc#example.com";
String user = "sp#example.com";
String pass = "1234";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.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(user,pass);
}
});
session.setDebug(true);
try
{
/* Create an instance of MimeMessage,
it accept MIME types and headers
*/
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(sub);
message.setText(msg);
/* Transport class is used to deliver the message to the recipients */
Transport.send(message);
}
catch(Exception e)
{
e.printStackTrace();
}
Error message:
535 5.7.3 Authentication unsuccessful javax.mail.AuthenticationFailedException at javax.mail.Service.connect(Service.java:319) at javax.mail.Service.connect(Service.java:169) at javax.mail.Service.connect(Service.java:118) at javax.mail.Transport.send0(Transport.java:188) at javax.mail.Transport.send(Transport.java:118) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPo‌​olExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.r‌​un(TaskThread.java:6‌​1) at java.lang.Thread.run(Thread.java:748)
SMTP configuration:
configuration:props.put("mail.smtp.host", "smtp.oceaneering.com"); props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
First is need to turn on 2-Step Verification .(after that google script to give new option for creation app passwords) https://support.google.com/accounts/answer/185839?
Next you must to create the app passwords https://support.google.com/accounts/answer/185833?hl=en
Last step to replace this line in your code
String pass = "1234"; - with app specific password, (it must generate on step 2) Some like String pass = "djd5n7hsd";
And For future reader in may be useful to check network and firewall setting on your system and mail setting your ISP. To check if packet can to reach gmail server.
Try telnet command : telnet smtp.gmail.com 587

SMTP Mail Sending Issue : com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay

I am trying to send mail from Java.
If i will send mail to same SMTP it working fine.
If i will send mail to outside SMTP means like Gmail, Yahoo etc. it'as shows error like,
[com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay][1]
ERROR :
SimpleEmail Start
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
Mail Send Successfully
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:124)
at com.nirav.java.project.demo.JavaMailSend.sendEmail(JavaMailSend.java:26)
at com.nirav.java.project.demo.NewSimpleMail.main(NewSimpleMail.java:34)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1917)
... 5 more
Code For Mail Sending :
try {
System.out.println("SimpleEmail Start");
String smtpHostServer = "XX.XX.XX.XXX";
final String toEmail = "XXXXXXXXXX#XXX.XXX";
final String fromEmail = "XXXXXXXXXX#XXX.XXX";
final String password = "XXXXXXXXXXXX";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.port", "25"); //If other then
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
//Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.addHeader("Content-type", "text/HTML; charset=UTF-8");
message.addHeader("format", "flowed");
message.addHeader("Content-Transfer-Encoding", "8bit");
message.setFrom(new InternetAddress("XXXXXX#XXX.XXX", "NoReply-JD"));
message.setReplyTo(InternetAddress.parse("XXXXXXXXX#XXX.XXX", false));
message.setSubject(subject, "UTF-8");
message.setText(body, "UTF-8");
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
Transport.send(message);
System.out.println("Mail Send Successfully");
} catch (Exception e) {
e.printStackTrace();
}
Please help me.
Thnaks.
Originally I was about to post this as comment, but it's too long.
The error is quite obvious, you are not allowed to use given SMTP server as relay. (What are SMTP relays?)
There are couple of reasons why this can happen:
You are not authenticated (need to login before sending)
Recipient is not in list of domains allowed to relay to
IP address from which you are connecting is not in white list (aka mynetworks in postfix context)
without providing more info (which SMTP server you are using, where are you sending mail, are you authenticated), I guess nobody will help you.
5.7.1 status code from IANA registry
The sender is not authorized to send to the destination. This can be
the result of per-host or per-recipient filtering. This memo does not
discuss the merits of any such filtering, but provides a mechanism to
report such. This is useful only as a permanent error.
Had this problem also but it was intermittent.
We have 2 servers that are within a cluster and on one the ip address of system that sends the email was not defined correctly.
Unfortunately the error message "javax.mail.SendFailedException: Invalid Addresses is confusing.
the 2nd error message: "com.sun.mail.smtp.SMTPAddressFailedException: 550 relay not permitted" matches much better.

Send mail using Gmail from Java without turning on less secure app

I am attempting to send mail using Java to a Gmail account, code below. I appear to be doing everything correctly, however I receive an authentication failure. Google wants me to turn on the "less secure app" feature to enable transmission.
Is there a way to code in such a way that Gmail is happy with Java and will not throw the "turn on less secure apps" fault?
Error:
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=...U
534-5.7.14 FigguJaZwDtp...
534-5.7.14 ...o> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/... - gsmtp
Code:
String hostSmtpUser = "myemail#gmail.com";
String host = "smtp.gmail.com";
String hostPort = "587";
String hostSmtpPassword = "thepassword";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.user", hostSmtpUser);
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.port", hostPort);
properties.setProperty("mail.smtp.auth", "true");
Session oSession;
if (true == ToolsCommon.isEmpty(hostSmtpUser))
oSession = Session.getInstance(properties);
else
oSession = Session.getInstance(properties, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(hostSmtpUser, hostSmtpPassword);
}
});
// Compose the message
try
{
MimeMessage message = new MimeMessage(oSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(Subject);
message.setText(Body);
// Send message
Transport.send(message);
}
catch (MessagingException ex)
{
// Log the error.
ToolsLog.logError(TypeLog.ui, ex);
}
I already did research, so the code to my knowledge is not the problem, just do not see a workaround for the less secure apps message.
References:
Ref 1
Ref 2
Ref 3
Ref 4
By default, GMail doesn't allow password-based authentication -- that's why you'd have to allow "less-secure apps" to use your program as-is.
Instead, you can use OAuth 2.0 to avoid using a password directly. That method is considered secure by Google and won't require changing any account settings.
Less secure apps (https://myaccount.google.com/u/0/lesssecureapps) options is disabled and we can longer use it to send mail.
But there is a better option provided by google - apppasswords
https://myaccount.google.com/u/0/apppasswords
Use 16 digit code provided by google instead of password and that should be it.
Note: 2-factor authentication needed to be enabled before using appspasswords.

How to send an email from Outlook via Java?

I am stuck behind a corporate firewall that won't let me send email via conventional means such as Java Mail API or Apache Commons Email, even to other people inside the organization(which is all I want anyways). But my Outlook 2010 obviously can send these emails. I was wondering if there is a way to automate Outlook 2010 via Java code so that Outlook can send the emails ? I know stuff like "mailto" can be used pop-up the default Outlook send dialog with pre-populated info, but I am looking for a way to have the send operation happen behind the scenes. Thanks for any info.
You can send emails through outlook with javamail use the configurations described on Outlook's official site.
Here is small demo code
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public static void main(String[] args) {
final String username = "your email"; // like yourname#outlook.com
final String password = "*********"; // password here
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp-mail.outlook.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiver mail")); // like inzi769#gmail.com
message.setSubject("Test");
message.setText("HI you have done sending mail with outlook");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
.
Note: I tested this with Javamail API 1.5.6
I don't think there's any way to do what you want using Outlook.
Presumably your mail server is also behind the corporate firewall. If you're using Outlook for your client, you're probably using Exchange for your server. Exchange can be configured to support the standard SMTP protocol for sending mail, which would allow use of JavaMail. If you can't configure your Exchange server to support SMTP, you still might be able to use Exchange Web Services. If that doesn't work, you might need to use one of the JavaMail Third Party Products that supports the Microsoft proprietary mail protocol.
Process p = Runtime.getRuntime().exec("cmd /C start outlook ");

Using JavaMail with TLS

I found several other questions on SO regarding the JavaMail API and sending mail through an SMTP server, but none of them discussed using TLS security. I'm trying to use JavaMail to send status updates to myself through my work SMTP mail server, but it requires TLS, and I can't find any examples online of how to use JavaMail to access an SMTP server that requires TLS encryption. Can anyone help with this?
We actually have some notification code in our product that uses TLS to send mail if it is available.
You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.
Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true"); // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props).
Good post, the line
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
is mandatory if the SMTP server uses SSL Authentication, like the GMail SMTP server does. However if the server uses Plaintext Authentication over TLS, it should not be present, because Java Mail will complain about the initial connection being plaintext.
Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.
The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.starttls.enable", "true");
Just use the following code. It is really useful to send email via Java, and it works:
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main {
public static void main(String[] args) {
final String username="your#gmail.com";
final String password="password";
Properties prop=new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String body="Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("receiver#gmail.com"));
message.setSubject("Testing Subject");
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
I just spent quite a bit of time figuring out how to use JavaMail to send emails with gmail or office365. I couldn't find the answer in the faq, but was helped a bit by the javadoc.
If you forget props.put("mail.smtp.starttls.enable","true") you get com.sun.mail.smtp.SMTPSendFailedException: 451 5.7.3 STARTTLS is required to send mail.
If you forget props.put("mail.smtp.ssl.protocols", "TLSv1.2"); you get javax.mail.MessagingException: Could not convert socket to TLS; and No appropriate protocol (protocol is disabled or cipher suites are inappropriate). Apparently this is only necessary for JavaMail versions 1.5.2 and older.
Here is the minimal code I required to get it to work:
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.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
// smtp.gmail.com supports TLSv1.2 and TLSv1.3
// smtp.office365.com supports only TLSv1.2
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test#example.com", "******");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender#example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient#example.com"));
message.setSubject("You got mail");
message.setText("This email was sent with JavaMail.");
Transport.send(message);
System.out.println("Email sent.");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
With Simple Java Mail 5.0.0 (simplejavamail.org) it is very straightforward and the library will take care of all the Session properties for you.
Here's an example using Google's SMTP servers:
Email email = EmailBuilder.startingBlank()
.from("lollypop", "lol.pop#somemail.com")
.to("C.Cane", "candycane#candyshop.org")
.withSubject("hey")
.withPlainText("We should meet up!")
.withHTMLText("<b>We should meet up!</b>")
.buildEmail();
MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
.buildMailer()
.sendMail(email);
If you have two-factor login turned on, you need to generate an application specific password from your Google account.
As a small note, it only started to work for me when I changed smtp to smtps in the examples above per samples from javamail (see smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip, option -S).
My resulting code is as follow:
Properties props=new Properties();
props.put("mail.smtps.starttls.enable","true");
// Use the following if you need SSL
props.put("mail.smtps.socketFactory.port", port);
props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.host", serverList.get(randNum));
Session session = Session.getDefaultInstance(props);
smtpConnectionPool = new SmtpConnectionPool(
SmtpConnectionFactories.newSmtpFactory(session));
final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
...
transport.sendMessage(message, message.getAllRecipients());

Categories