How to connect to office365 using IMAPS protocol from Java application - java

There are few articles out there about this, but non of them worked for me. Basically I have following java code to connect to office 365:
Properties props = new Properties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.imaps.ssl.enable", "true");
session = Session.getInstance(props, null);
store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
but it fails with LOGIN failed error;
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:725)
at javax.mail.Service.connect(Service.java:366)
Also I'm able to login into my account using IMAPS from Thunderbird.
Any pointers to resolve an issue would be appreciated!

This code works for me for outlook I have modified it for use with Office365. I did the research to find the IMAP host for office 365. I hope it helps you.
public static void main(String[] args) throws MessagingException {
MultiPartEmail email = new MultiPartEmail();
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
//extra codes required for reading OUTLOOK mails during IMAP-start
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
//extra codes required for reading OUTLOOK mails during IMAP-end
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", "some.one#some.org", "mypassword");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
inbox.addMessageCountListener(new MessageCountListener() {
#Override
public void messagesAdded(MessageCountEvent messageCountEvent) {
Message[] messages = messageCountEvent.getMessages();
System.out.println("A message was added, you now have: " + messages.length + " emails");
}
#Override
public void messagesRemoved(MessageCountEvent messageCountEvent) {
}
});
while (true) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
inbox.getMessageCount(); // Keeps connection alive
}
}

As it turned out, office 365 was rejecting connections because of unsupported characters inside the password. Particularly quote character. So, as simple as changing psw fixed my problem.
And following code snippet works just fine:
Properties props = new Properties();
props.put("mail.store.protocol", "imaps");
session = Session.getInstance(props, null);
store = session.getStore();
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
With 'javax.mail', version: '1.5.6'

Related

How to Email execution report in selenium web-driver java without jenkins?

I have tried to use apache common mail API. the code i used is
public static void main(String[] args) throws EmailException {
System.out.print("-------Start------");
// TODO Auto-generated method stub
Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(userName, password));
email.setSSLOnConnect(true);
email.setFrom("user#gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("myemail#gmail.com");
email.send();
System.out.print("-------End------");
}
but It is saying username and password not accepted however i am providing the correct credentials. When i opened my gmail account , it is showing that it has blocked the sign in attempt. Is there any other way to achieve this?
Please download https://github.com/javaee/javamail/releases
And follow the example below on how to setup Gmail using JavaMail. You dont need any webdriver for this. The javamail jar in your classpath is sufficient.
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#gmail.com"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("to_username_a#gmail.com, to_username_b#yahoo.com")
);
message.setSubject("Testing Gmail TLS");
message.setText("Dear Mail Crawler,"
+ "\n\n Please do not spam my email!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
If still having trouble, you might need to use and trust an APP Password.
https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor
Create & use App Passwords
If you use 2-Step-Verification and get a "password incorrect" error when you sign in, you can try to use an App Password.
Go to your Google Account.
Select Security.
Under "Signing in to Google," select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
2-Step Verification is not set up for your account.
2-Step Verification is only set up for security keys.
Your account is through work, school, or other organization.
You turned on Advanced Protection.
At the bottom, choose Select app and choose the app you using and then Select device and choose the device you’re using and then Generate.
Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
Tap Done.
Tip: Most of the time, you’ll only have to enter an App Password once per app or device, so don’t worry about memorizing it.
Reference: https://mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Running JavaMail API in Gradle Project on Eclipse

I have a Gradle project in my Eclipse IDE and I need to be able to send an e-mail receipt as part of a school project. I looked at this link http://www.tutorialspoint.com/java/java_sending_email.htm to try and create the most basic e-mail. I've tried the "sending a simple e-mail" example and I got this as my error:
Usage - java org.mortbay.jetty.Main [<addr>:]<port>
Usage - java org.mortbay.jetty.Main [<addr>:]<port> docroot
Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapp myapp.war
Usage - java org.mortbay.jetty.Main [<addr>:]<port> -webapps webapps
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port>
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> docroot
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapp myapp.war
Usage - java -jar jetty-x.x.x-standalone.jar [<addr>:]<port> -webapps webapps
I'm guessing I don't have the JavaMail API and Java Activation Framework (JAF) properly installed. I've followed some guides on how to do that. What I've done was right click gradle project -> Properties -> Java Build Path -> Libraries tab -> Add External JARs.. And I added the JAF and JavaMail jar files (activation-1.1.1.jar and mail-1.4.5.jar). I also added
compile group: 'javax.mail', name: 'mail', version: '1.4.5'
compile group: 'javax.activation', name: 'activation', version: '1.1.1'
to my build.gradle file. Any help on how to get this working would be greatly appreciated.
Here is the code I used.
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
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 = "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);
// 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();
}
}
}
You have to give proper settings to send email. like
String host = "localhost"; // instead of localhost you have to give your hostname.
If you want to send mail via gmail, use the following code:
SendEmail.java
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 class SendEmail{
public static void main(String[] args) {
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");
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("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Welcome Message");
Transport.send(message);
System.out.println("Mail Sent Successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Cannot fetch Gmail inbox with JavaMail POP

I'm trying to fetch unread messages from Gmail inbox with Javamail, but I can't. I only retrieve archived messages (from 2011!!!) and I don't know why or how to do it.
Here is my code:
public List<DefaultMessage> getLatestNthMessages(Integer numberOfMessages) throws Exception {
URLName url = new URLName("pop3", "pop.gmail.com", 995, "",username, password);
Store store = new POP3SSLStore(pullSession, url);
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
SearchTerm st = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
List<Message> msgs = Arrays.asList(inbox.search(st)).stream()
.sorted((m1, m2) -> m2.getMessageNumber() - m1.getMessageNumber())
.limit(numberOfMessages)
.collect(Collectors.toList());
List<DefaultMessage> listOfMessages = new ArrayList<>();
for (Message message : msgs) {
listOfMessages.add(wrapperToMessage(message));
}
return listOfMessages;
}
pullSession is instantiated as follows:
Properties pullProps = new Properties();
pullProps.put("mail.pop3.host", pullHost);
pullProps.put("mail.pop3.username", username);
pullProps.put("mail.pop3.port", pullPort);
pullProps.put("mail.pop3.socketFactory.port", pullPort);
pullProps.put("mail.pop3.socketFactory.fallback", "false");
pullProps.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
pullProps.put("mail.pop3.auth", "true");
pullSession = Session.getInstance(pullProps, null);
pullSession.setDebug(true);
Check your Gmail settings for POP3.
Also, there's lots of things you can improve in your code, although they're not the source of your problem. Start by fixing all the common JavaMail mistakes.
You should not be creating a POP3SSLStore directly. Use the Gmail example code in the JavaMail FAQ.

Java send mail, Takes time in Activation

I need to send a mail using SMTP of Gmail, and javax.mail api.
The same code I'm using, runs successfully in Android, If I take it to a Java Application or tries to use it in a Java Web Application it starts making troubles.
I spent time trying to understand what is the difference but no way!
My code is as following:
public class GMailSender extends Authenticator
{
private final String mailhost;
private final String password;
private final Session session;
private final String user;
public GMailSender(String username, String password)
{
this.mailhost = "smtp.gmail.com";
this.user = username;
this.password = password;
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.host", mailhost);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.debug", "true");
properties.setProperty("mail.smtp.quitwait", "false");
System.out.println("Creating session ...");
session = Session.getInstance(properties, this);
System.out.println("Session createed ...");
}
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
System.out.println("Authintecation ...");
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String dataHandler, String senderAddress, String recepeintAddress)
throws Exception
{
MimeMessage mimemessage;
mimemessage = new MimeMessage(session);
DataHandler datahandler = new DataHandler(new ByteArrayDataSource(dataHandler.getBytes(), "text/plain"));
mimemessage.setSender(new InternetAddress(senderAddress));
mimemessage.setSubject(subject);
mimemessage.setDataHandler(datahandler);
mimemessage.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recepeintAddress));
System.out.println("Sending ...");
Transport transport = session.getTransport("smtp");
transport.send(mimemessage);
System.out.println("Sent!");
}
static {
Security.addProvider(new JSSEProvider());
}
public static void main(String[] args){
System.out.println("Starting email ...");
GMailSender sender = new GMailSender("myEmail#gmail.com", "my password");
try {
sender.sendMail("Test", "alot of data", "myEmail#gmail.com", "someonesemail#gmail.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public final class JSSEProvider extends Provider {
private static final long serialVersionUID = 1L;
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController
.doPrivileged(new java.security.PrivilegedAction<Void>() {
#Override
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
When I run my code I got the following:
> Starting email ...
> Creating session ...
> Session createed ...
> Sending ...
> Authintecation ...
Then it takes around 10 min to return with the following:
> javax.mail.MessagingException: Could not connect to SMTP host:
> smtp.gmail.com, port: 465, response: -1
> at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1379)
> at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
> at javax.mail.Service.connect(Service.java:310)
> 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)
> at com.srycrm.mail.GMailSender.sendMail(GMailSender.java:66)
> at org.apache.jsp.send_jsp._jspService(send_jsp.java:85)
> at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
> at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
> at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
> at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
> at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
> at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
> at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Anyone can help me please!!
Thank you.
Ok you are using port 465, so enable ssl mail.smtp.ssl.enable to true :
properties.put("mail.smtp.ssl.enable", "true");
if it doesn;t work , then have properties.put("mail.smtp.starttls.enable", "true"); and change port to 587 and see if it helps.
Great!
Thanks for all the people that tried to help.
The Solution is a bit strange! I just downgraded my JRE and JDK to 1.6 and this solved the problem!
It might be something with the Java 1.7 enviroment.
Anyway, Thanks for all you are like always awesome :)
There's a bunch of errors in your code. Start here to fix the most common mistakes.
After that, see the JavaMail FAQ for connection debugging tips. Post the debug output here if you can't figure it out.

JavaMail SocketException: Connection reset

I'm trying to send emails through JavaMail API but I end up receiving the SocketException: Connection reset.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMailSSL {
public static void main(String[] args) {
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");
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("userName#gmail.com","gmailPassword");
}
};
Session session = Session.getDefaultInstance(props,auth);
try {
Message message = new MimeMessage(session);
Address sender = new InternetAddress("any#...");
message.setFrom(sender);
String recipients = "email1#...,email2#...,email2#...";
String[] toList = recipients.split(",");
System.out.println(toList.length);
Address[] addressTo = new InternetAddress[toList.length];
for(int i = 0; i < toList.length; i++){
addressTo[i] = new InternetAddress(toList[i]);
}
for( int i=0; i < addressTo.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, addressTo[i]);
}
message.setSubject("Testing Subject 5");
message.setText("Dear Message ," +
"\n\n HELLO, please! \n https://192.168.192.120:8181/centralWeb");
System.out.println("SENDING MAIL......... " + new Date().toString());
message.setHeader("Content-type", "text/html; charset=UTF-8");
Transport.send(message);
System.out.println("Done " + new Date().toString());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
NetBeans Output:
1
SENDING MAIL......... Sun Apr 28 01:30:18 IST 2013
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at sendmailssl.SendMailSSL.main(SendMailSSL.java:65)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at sendmailssl.SendMailSSL.main(SendMailSSL.java:60)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:312)
at sun.security.ssl.InputRecord.read(InputRecord.java:350)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:503)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
... 7 more
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I've tried disabling IPv6 and turning off my firewall too, but the problem persists. I am using Windows 7 x64, if that matters.
Thanks to anyone who can help me fix this issue.
Try these debugging tips from the JavaMail FAQ:
How do I debug my application that uses JavaMail APIs?
How do I debug problems connecting to my mail server?
Also, you might want to correct these common mistakes, although I don't think they're related to your problem.

Categories

Resources