Not able to send Mail in Java through SMTP server - java

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

Related

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.

Unknown SMTP host: outlook.office365.com;

I have written code in java to send mail. The issue I am facing is UnknownHostException. I am using SMTP Host as outlook.office.com as the email account from where i want to send the mail is corporate and accessed using outlook. Here is the code.
Properties props=new Properties();
props.put("mail.smtp.auth","true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host","outlook.office365.com");
props.put("mail.smtp.port","587");
Session session=Session.getInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(sender, password);
}
});
The session object is not null as I have put a check on that. If session is getting created then what is the reason I am facing this exception?
change
props.put("mail.smtp.host","outlook.office365.com");
to
props.put("mail.smtp.host","smtp.office365.com");
or
props.put("mail.smtp.host", "m.outlook.com");
for more info, visit this and this site.

tried tjavax.mail.MessagingException: Unknown SMTP host: "smtp.office365.com";

I am getting this error when I try to send an email from Java web app hosted on AWS.
I have already tried to change SMTP server to smtp.live.com and also smtp-mail.outlook.com, none of those work.
Can it be some AWS config? It runs on Ubuntu. (There are no outbound restrictions on the server itself, there might be some on Java server though)
Code for sending the email:
final String username = smtpUsername;
final String password = smtpPwd;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
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(smtpUsername));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
message.setSubject(subject);
message.setContent(content);
Transport.send(message);
System.out.println("Sent");
} catch (MessagingException e) {
e.printStackTrace();
}
The most interesting part of this is, that it works from my local computer...(but only when I disable Avast)
I have tried to execute telnet smtp.office365.com 587 and the result was:
Trying 132.245.195.162...
Connected to outlook-emeawest2.office365.com.
Escape character is '^]'.
220 HE1PR08CA0021.outlook.office365.com Microsoft ESMTP MAIL Service ready at Wed, 26 Aug 2015 14:32:11 +0000
I have tried to set up the AWS SMTP (SES) and I am getting the same error, even after I followed the documentation, I also added the email from which I was sending and to which I was sending to the verified emails (whitelist):
javax.mail.MessagingException: Unknown SMTP host: "email-smtp.eu-west-1.amazonaws.com";
try doing a dig from a bash shell from the ubuntu machine
dig email-smtp.eu-west-1.amazonaws.com
what are you getting. from what I can see, it might be a DNS problem.

Send Java email without authentication (no such provider exception: smtp)

The code I am currently using is as follows:
String to = "....#gmail.com";
String from = ".....#gmail.com";
String host = "127.0.0.1";
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("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
If I paste the above code in my Java servlet and run it, the following exception gets thrown:
javax.mail.NoSuchProviderException: smtp
I have also tried following the solutions outlined in these resources but to no avail: link1 link2 link3 link4.
It would help if you included the the full stacktrace for the javax.mail.NoSuchProviderException and JavaMail debug output. Because you are running this in a servlet container you could be running into Bug 6668 -skip unusable Store and Transport classes. Change your call to Transport.set to the following:
final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Session.class.getClassLoader());
try {
Transport.send(message);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
That code will isolate which transport class the code is allowed to see. That will rule out that bug in your code.
NoSuchProviderException means something is messed up in your JavaMail API configuration. Where and how have you installed the JavaMail jar file?
Also, in case it's not clear from the other responses, the only way you're going to be able to send mail without authentication is if you're running your own mail server. You can't do it with general purpose online e-mail services (e.g. Gmail).
First of all, if you wanna use gmail to send emails from your program you need to define stmp host as gmail. Your current host "127.0.0.1" is localhost meaning your own computer? Do you have mail server running on your computer?
Here you can see some tutorial how to send an email using gmail: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
If you're afraid to pass your normal gmail account details then create some kind of test email like kselvatest or something.
You are missing pretty much those:
final String username = "username#gmail.com";
final String password = "password";
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");
So basicly all you need to add is:
1.login and password so JavaMail can use some gmail account
2.declare which mail server you wanna use
change String host = "127.0.0.1"; to String host = "smtp.gmail.com";
3.set mail port
For this code you should get javax.mail.MessagingException: Could not connect to SMTP host: 127.0.0.1, port: 25; exception
But I suspect you have a jre issue. May be smtp implementation has a problem. Why don't you download java mail implementation from http://www.oracle.com/technetwork/java/javamail/index-138643.html and add it to your project class path and try?

JavaMail cannot send email

i am trying to write an application in java that will send emails, i found a tutorial on youtube and tried to follow it. however it does not work for me still, here is the error i get
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25, response: 421
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1949)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
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 libraryFineList.ParseRecords.main(ParseRecords.java:90)
i have no idea, what's wrong, anything i found on google did not help,
here is the code
public static void main(String[] args) throws IOException, MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
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("user#gmail.com", "pass");
}
}
);
try{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("user#gmail.com"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("ycharnetskaya#gmail.com", "Mr. User"));
message.setSubject("Your Example.com account has been activated");
message.setText("Worked");
Transport.send(message);
}catch(Exception e){
e.printStackTrace();
}
The tutorial you followed is full of errors. Start by fixing these common mistakes. Then follow these instructions for connecting to Gmail. If you're still having problems, you'll find lots more help in the JavaMail FAQ. There's also many sample programs available.
It's strange that your error message is complaining about a problem connecting to localhost:25 when your properties file is clearly suggesting that you should use smtp.gmail.com.
I don't suppose there's anything dodgy going on with your hosts file that's redirecting smtp.gmail.com back to 127.0.0.1 or something, is there? What happens if you ping smtp.gmail.com from the command line?
Apart from that, I'd suggest checking you're using the latest version of Java Mail.

Categories