javax.mail.AuthenticationFailedException: AUTHENTICATE failed. IMAP Store is not connecting - jakarta-mail

I am not able to connect to IMAP store . It was working earlier now its throwing below error
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:474)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:176)
Code:
Properties properties = new Properties();
properties.put("mail.imap.host", "outlook.office365.com"));
properties.put("mail.imap.port", "993");
properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.imap.socketFactory.fallback", "false");
properties.setProperty("mail.imap.socketFactory.port", String.valueOf("993")));
session = Session.getInstance(properties);
store = session.get("imap");
store.connect(username,password);
I checked all the links , i tried few solutions suggested but they dint work .
Debug Info.
DEBUG: JavaMail version 1.4ea
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.8.0_112\jre\lib\javamail.providers (The system cannot find the file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jdk1.8.0_112\jre\lib\javamail.address.map (The system cannot find the file specified)
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
* OK The Microsoft Exchange IMAP4 service is ready. [TQBBADEAUABSADAAMQAwADEAQwBBADAAMAA2ADcALgBJAE4ARABQAFIARAAwADEALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
A0 OK CAPABILITY completed.
IMAP DEBUG: AUTH: PLAIN
IMAP DEBUG: AUTH: XOAUTH2
DEBUG: protocolConnect login, host=outlook.office365.com, user=pavkumar0#publicisgroupe.net, password=<non-null>
A1 AUTHENTICATE PLAIN
+
cGF2a3VtYXIwQHB1YmxpY2lzZ3JvdXBlLm5ldABwYXZrdW1hcjBAcHVibGljaXNncm91cGUubmV0AFNyaWRoYWJ2cmsrMTM=
A1 NO AUTHENTICATE failed.
javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:474)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)

Authentication failed error was coming as the Imap for the account was not enabled at firewall.

I also had this issue in reading emails from an outlook office365 account which was upgraded recently.
I changed code to use microsoft ews-java-api and issue resolved.
Example code to make connection and read emails with attachment and passed subject using microsoft ews-java-api:
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.PropertySet;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.service.schema.ItemSchema;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.FileAttachment;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.core.service.folder.Folder;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;
import org.springframework.util.CollectionUtils;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
public class ExchangeEmailTest {
public static void main(String[] args) {
try {
ExchangeService service = createConnection();
readAttachmentEmail(service);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static ExchangeService createConnection() throws Exception {
String email = "your email";
String password= "your email password";
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials(email, password);
service.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
service.setCredentials(credentials);
return service;
}
private static void readAttachmentEmail(ExchangeService service) throws Exception {
// Bind to the Inbox.
Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
// set number of items you want to retrieve
ItemView view = new ItemView(1);
List<SearchFilter> searchFilterCollection = new ArrayList<>();
// flag to pick only email which contains attachments
searchFilterCollection.add(new SearchFilter.IsEqualTo(ItemSchema.HasAttachments, Boolean.TRUE));
searchFilterCollection.add(new SearchFilter.ContainsSubstring(ItemSchema.Subject,"subject filter"));
SearchFilter finalSearchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
ArrayList<Item> items = service.findItems(inbox.getId(), finalSearchFilter, view).getItems();
if(!CollectionUtils.isEmpty(items)) {
Item item= items.get(0);
System.out.println("id==========" + item.getDateTimeReceived());
System.out.println("sub==========" + item.getSubject());
EmailMessage message = EmailMessage.bind(service, item.getId(), new PropertySet(ItemSchema.Attachments));
FileAttachment attachment = (FileAttachment) message.getAttachments().getItems().get(0);
attachment.load(" < attachment save directory > "+attachment.getName());
}
}
}

Instead of giving the plain password,create a app password and use it.It will work.
Steps Login to Office 365 Got MYAccount-->Security and Privacy-->Additional security verification-->Create and manage app passwords
Just use the below properties only
Properties props = new Properties();
props.put("mail.imap.host", "outlook.office365.com");
props.setProperty("mail.imap.starttls.enable", "true");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.debug", "true");

I faced the same issue for gmail account when i try to run the code in different device .It is because the google will not allow the gmail account to login to other device .Solution to this is you should allow access to the account using below url :
https://accounts.google.com/DisplayUnlockCaptcha

Related

invalid_token_response An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: 401 Unauthorized: [no body]

I have added Azure AD as an authentication server but it is showing me the following error
[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: 401 Unauthorized: [no body]
Springboot: 2.5.8
Azure version: 3.10.0
my application.properties:
spring.security.oauth2.client.registration.azure-client.provider=azure-ad
spring.security.oauth2.client.registration.azure-client.client-id=<Client_id>
spring.security.oauth2.client.registration.azure-client.client-secret=<Client_secret>
spring.security.oauth2.client.registration.azure-client.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.azure-client.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
spring.security.oauth2.client.registration.azure-client.scope=openid, profile
spring.security.oauth2.client.registration.azure-client.client-authentication-method=post
spring.security.oauth2.client.provider.azure-ad.authorization-uri=https://login.microsoftonline.com/common/oauth2/v2.0/authorize
spring.security.oauth2.client.provider.azure-ad.token-uri=https://login.microsoftonline.com/common/oauth2/v2.0/token
spring.security.oauth2.client.provider.azure-ad.jwk-set-uri=https://login.microsoftonline.com/common/discovery/v2.0/keys
spring.security.oauth2.client.provider.azure-ad.user-name-attribute=name
server.forward-headers-strategy=native
logging.level.org.springframework.security=DEBUG
And SecurityConfig class:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure( HttpSecurity http ) throws Exception {
http.authorizeRequests()
.antMatchers( "/oauth2/**", "/login/**" ).permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.defaultSuccessUrl( "/home" );
}
}
And Controller:
#RestController
public class HomeController {
#GetMapping( "home" )
public String home( #AuthenticationPrincipal(expression = "claims['name']") String name ) {
return String.format( "Hello %s! welcome to the Security app", name);
}
}
On Work around
Solution 1:
Make sure you have entered the correct TenantID, ApplicationID and Application_Secret, and the Group name in the application.properties file
and also the scopes your app is requesting have been configured (if admin consent is required, please grant it) in Azure Portal.
Solution 2:
Try with changing the the azure endpoints from v2 to v1. This is done by changing the endpoints
e.g. http://login.microsoft.com/common/oauth2/v2.0/authorize
becomes http://login.microsoft.com/common/oauth2/authorize as indicated in the v1 & v2 comparison.
For more information about v1 refer this document
For more details refer this SO Thread:

How to configure IdentityServerAuthenticationOptions.Authority to use wildcards

I successfully setup IdentityServer4 with ASP.NET Core.
As a default config I had this:
IdentityServerAuthenticationOptions options = new IdentityServerAuthenticationOptions()
{
Authority = "http://localhost:5000",
ScopeName = "scope",
ScopeSecret = "ScopeSecret",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
RequireHttpsMetadata = false,
};
Now, using this guide I configured to be read from configuration files and so they can be any numbers in production.
For example if I setup API to be running at http://*:5000 then the client can connect to it via the service IP address like http://192.168.1.100:5000.
Once the client obtains the Bearer token and tries to use it, an Internal Server Error occures with this exception:
Unable to obtain configuration from:
'http://*:5000/.well-known/openid-configuration'.
---> System.IO.IOException: IDX10804: Unable to retrieve document from: 'http://*:5000/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
What is the correct way to configure IdS4 to have dynamic authority?
Update
It seems the problem is with Issuer, any idea on this?
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException:
IDX10205: Issuer validation failed. Issuer: 'http://192.168.1.100:5000'. Did not match: validationParameters.ValidIssuer: 'http://localhost:5000' or validationParameters.ValidIssuers: 'null'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateIssuer(String issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
By a big surprise, all I needed, was to set a value (almost any value) for IssuerUri:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
////...
var identiyBuilder = services.AddIdentityServer(options =>
{
options.RequireSsl = false;
options.IssuerUri = "MyCompany";
});
////...
}
Now, by the above config, I can use the service by any IP address.
I didn't find I could just put in MyCompany
But in my log files I had the following:
Bearer was not authenticated. Failure message: IDX10205: Issuer validation failed. Issuer: 'https://crm.example.com'. Did not match: validationParameters.ValidIssuer: 'MyCompany' or validationParameters.ValidIssuers: 'null'.
I don't quite know what 'issuer' means but I was able to just take 'https://crm.example.com' and get things working with this :
options.IssuerUri = "https://crm.example.com";

Spring Turbine dashboard not working

I am facing some issue while working on turbine dashboard. As I am able to get turbine stream for given cluster but not able to see anything on dashboard as it is just getting loaded as shown in below screenshots. Kindly help if any configuration is missing.
Below are my configurations:
config.properties
turbine.aggregator.clusterConfig=SpringHystrixDemo2
turbine.instanceUrlSuffix=:9080/hystrix.stream
turbine.EurekaInstanceDiscovery.hystrix2.instances=localhost
InstanceDiscovery.impl=com.netflix.turbine.discovery.EurekaInstanceDiscovery.class
turbine.InstanceMonitor.eventStream.skipLineLogic.enabled=false
Application.yml
server:
port: 8080
turbine:
aggregator:
clusterConfig: SPRINGHYSTRIXDEMO2
clusterNameExpression: new String("default")
appConfig: SpringHystrixDemo2
InstanceMonitor:
eventStream:
skipLineLogic:
enabled: false
bootstrap.yml
spring:
application:
name: SpringTurbine
cloud:
config:
discovery:
enabled: true
eureka:
instance:
nonSecurePort: ${server.port:8080}
client:
serviceUrl:
defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/
Application.java
#SpringBootApplication
#EnableHystrix
#EnableEurekaClient
#EnableHystrixDashboard
#EnableTurbine
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
For cluster SpringHystrixDemo2 I have configured it in different application running on other port:
application.yml -
server:
port: 9080
hystrix:
command:
RemoteMessageClientCommand:
execution:
isolation:
thread:
timeoutInMilliseconds: 5000
RemoteMessageAnnotationClient:
execution:
isolation:
thread:
timeoutInMilliseconds: 5000
bootstrap.yml
spring:
application:
name: SpringHystrixDemo2
cloud:
config:
enabled: true
discovery:
enabled: true
serviceId: SPRINGCONFIGSERVER
eureka:
instance:
nonSecurePort: ${server.port:9080}
client:
serviceUrl:
defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/
Application.java - this is from hystrix dashboard service.
#SpringBootApplication
#EnableHystrix
#EnableHystrixDashboard
#EnableEurekaClient
#EnableDiscoveryClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
I have configured eureka server on 8761 port. which is lisening all other eureka client.as
Eureka server
This is how I am not able to see any turbine dashboard. as it is just getting loaded.
turbine stream view
First thing that comes to my mind is that you could declare a management endpoint like this:
management:
port: 9081
contextPath: /management
Then the turbine stream would be accesible via {yourHost}:9081/management/turbine.stream, while hystrix dashboard will be served under {yourhost}:9080/hystrix
From what I have read and known, from your configuration
turbine.aggregator.clusterConfig=SpringHystrixDemo2
turbine.instanceUrlSuffix=:9080/hystrix.stream
turbine.EurekaInstanceDiscovery.hystrix2.instances=localhost InstanceDiscovery.impl=com.netflix.turbine.discovery.EurekaInstanceDiscovery.class
turbine.InstanceMonitor.eventStream.skipLineLogic.enabled=false
following maybe the problem(s).
You are short of a few configs and maybe you have some extra configs too.
You do not need "turbine.EurekaInstanceDiscovery.hystrix2.instances" unless you really have multiple instances.
You do not need "turbine.InstanceMonitor.eventStream.skipLineLogic.enabled" because its false by default, and its required if you want it to be true when u you have high latency.
you need "turbine.appConfig=". In your case i think its something like SpringHystrixDemo2 or maybe hystrix2 ... use proper name here.
you need "turbine.aggregator.clusterConfig=" which worked for me only when i used in CAPITAL i.e. HYSTRIX2
if you are using different management port on your service, "turbine.instanceUrlSuffix.HYSTRIX2=:/hystrix.stream
then this "turbine.instanceInsertPort=false" will disable default port insertion by turbine.. basically, you are telling eureka not to insert any port on its own when trying to search for hystrix.strem..
following are my properties.
#turbine.clusterNameExpression=new String('default')
#turbine.clusterNameExpression="'default'"
turbine.instanceInsertPort=false
turbine.appConfig=service1
turbine.aggregator.clusterConfig=SERVICE1
turbine.instanceUrlSuffix.SERVICE1=:51512/hystrix.stream
#turbine.ConfigPropertyBasedDiscovery.USER.instances=service1-host1.abc.com,service1-host2.abc.com
InstanceDiscovery.impl=com.netflix.turbine.discovery.EurekaInstanceDiscovery.class
#for high latencies
#turbine.InstanceMonitor.eventStream.skipLineLogic.enabled=false
and try the turbine stream on
http://host:port/turbine.stream?cluster=SERVICE1

FloderClosedException while retrieving from dummy green mail imap server

I have created a dummy green mail server to simulate a mailbox for my application.
My application basically connects to a mail server and retrieves new mails based on some criteria. So i have created a dummy mail server for my application using green mail.
Now when I start my green mail and afterwards when try to connect to the mailbox created by green mail by my original application(application under test) then the application is able to connect to it and able to read list of new mails from the green mail server but when i try to read parameters of the fetched then it says-:
javax.mail.FolderClosedException: * BYE JavaMail Exception: java.io.IOException: Connection dropped by server?
at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1428)
at com.sun.mail.imap.IMAPMessage.getSubject(IMAPMessage.java:427)
at greenmailtest.ImapIT.getMails(ImapIT.java:79)
at greenmailtest.ImapIT.main(ImapIT.java:94)
I am attaching my test code here:-
public void setUp() {
mailServer = new GreenMail(ServerSetupTest.IMAP);
mailServer.start();
}
public void tearDown() {
mailServer.stop();
}
public void getMails() throws IOException, MessagingException,
UserException, InterruptedException {
// create user on mail server
GreenMailUser user = mailServer.setUser(EMAIL_USER_ADDRESS, USER_NAME,
USER_PASSWORD);
// create an e-mail message using javax.mail ..
File file=new File("/home/sameepsinghania/Desktop/HDFC/Addcalbackfailure.png");
// byte[] byteArray=TestMailUtil.readContentIntoByteArray(file);
MimeMultipart multipart=TestMailUtil.createMultipartWithAttachment(EMAIL_TEXT,file, "sameep.png");
MimeMessage message = new MimeMessage((Session) null);
message.setFrom(new InternetAddress(EMAIL_TO));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
EMAIL_USER_ADDRESS));
message.setSubject(EMAIL_SUBJECT);
message.setContent(multipart);
// use greenmail to store the message
user.deliver(message);
Properties props = new Properties();
Session session = Session.getInstance(props);
URLName urlName = new URLName("imaps", "127.0.0.1",
ServerSetupTest.IMAP.getPort(), null, user.getLogin(),
user.getPassword());
Store store = session.getStore(urlName);
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
for(Message message1: messages){
System.out.println("subject "+message1.getSubject());//**this is the line where I get the exception**
}
}
JavaMail Debug logs-:
DEBUG: setDebug: JavaMail version 1.5.3
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle]
DEBUG IMAP: mail.imap.fetchsize: 16384
DEBUG IMAP: mail.imap.ignorebodystructuresize: false
DEBUG IMAP: mail.imap.statuscachetimeout: 1000
DEBUG IMAP: mail.imap.appendbuffersize: -1
DEBUG IMAP: mail.imap.minidletime: 10
DEBUG IMAP: closeFoldersOnStoreFailure
DEBUG IMAP: trying to connect to host "127.0.0.1", port 3143, isSSL false
* OK IMAP4rev1 Server GreenMail ready
A0 CAPABILITY
* CAPABILITY IMAP4rev1 LITERAL+ QUOTA
A0 OK CAPABILITY completed.
DEBUG IMAP: protocolConnect login, host=127.0.0.1, user=hascode, password=<non-null>
DEBUG IMAP: LOGIN command trace suppressed
DEBUG IMAP: LOGIN command result: A1 OK LOGIN completed.
A2 CAPABILITY
* CAPABILITY IMAP4rev1 LITERAL+ QUOTA
A2 OK CAPABILITY completed.
DEBUG IMAP: connection available -- size: 1
A3 EXAMINE INBOX
* FLAGS (\Answered \Deleted \Draft \Flagged \Seen)
* 1 EXISTS
* 1 RECENT
* OK [UIDVALIDITY 1461648432354]
* OK [UNSEEN 1] Message 1 is the first unseen
* OK [PERMANENTFLAGS (\Answered \Deleted \Draft \Flagged \Seen)]
A3 OK [READ-ONLY] EXAMINE completed.
A4 FETCH 1 (ENVELOPE INTERNALDATE RFC822.SIZE)
javax.mail.FolderClosedException: * BYE JavaMail Exception: java.io.IOException: Connection dropped by server?
at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1428)
at com.sun.mail.imap.IMAPMessage.getSubject(IMAPMessage.java:427)
at greenmailtest.ImapIT.getMails(ImapIT.java:78)

javax.mail.MessagingException: Connection reset while trying to access gmail using java mail API

I was trying to read through the mails in my gmail account using java mail API. This is the code:
import java.util.*;
import java.io.*;
import java.awt.*;
import javax.mail.*;
import javax.mail.search.FlagTerm;
import javax.mail.Flags.Flag;
public class MailPharser {
/**
* #param args
*/
public void mailRead()
{
Folder inbox;
// TODO Auto-generated method stub
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com","<mailid#gmail.com>", "<password>");
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
}
catch (Exception ex)
{ System.out.println("Error caught"); ex.printStackTrace(); }
}
public static void main(String[] args) {
MailPharser mp = new MailPharser();
mp.mailRead();
}
}
While running, i am getting the below error:
javax.mail.MessagingException: Connection reset;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at MailPharser.mailRead(MailPharser.java:26)
at MailPharser.main(MailPharser.java:40)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:113)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:111)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:637)
... 4 more
I added trace and see that the connect call is failing. Am i doing anything wrong? any help would do. thanks in advance...
It's probably a network problem unrelated to JavaMail, e.g., a proxy or firewall between you and Gmail.
If you want to find out whether it's your code that's broken or the network that's broken, you can test using the code that comes with JavaMail. If the JavaMail code works, then you know there's something wrong with your code, and you can use the JavaMail code in the FAQ to improve your code.
If you discover that it's a network problem, the JavaMail FAQ also has tips for debugging it further.

Resources