Fetch email using JavaxMail and Proxies - java

I'm trying to connect to a mail server using IMAP protocol and proxies with the JavaxMail library. Yet they seem not to work.
Properties properties = new Properties();
List<Message> messages = new ArrayList<>();
Host host = Host.getHostByMail(mail);
properties.put("proxySet", "true");
properties.put("mail.imap.proxy.host", "proxy host");
properties.put("mail.imap.proxy.port", "proxy port");
properties.put("mail.imap.proxy.user", "proxy user");
properties.put("mail.imap.proxy.password", "proxy passwd");
properties.put("mail.imap.host", host.toString());
properties.put("mail.imap.port", "143");
properties.put("mail.imap.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imap");
store.connect(host.toString(), mail, passwd);
Folder readOnly = store.getFolder("INBOX");
readOnly.open(Folder.READ_ONLY);
FlagTerm unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
When I try to use this code it gives me this error:
Exception in thread "Timer-2" com.sun.mail.util.MailConnectException: Couldn't connect to
host, port: imap.tiscali.it, 143; timeout -1; Using web proxy host, port: proxy_host, proxy_port; nested exception is:
java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at mail.MailHandler.readMail(MailHandler.java:97)
at mail.MailHandler.readAllMail(MailHandler.java:143)
at mail.MailSender.onCall(MailSender.java:27)
at commands.Temp$1.run(Temp.java:21)
at java.base/java.util.TimerThread.mainLoop(Timer.java:566)
at java.base/java.util.TimerThread.run(Timer.java:516)
Caused by: java.net.ConnectException: connection through proxy proxy_host:proxy_port to imap.tiscali.it:143 failed: HTTP/1.1 403 Forbidden
at com.sun.mail.util.SocketFetcher.proxyConnect(SocketFetcher.java:877)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 8 more
This happens when I use HTTP/HTTPS proxies, but when I use SOCKS proxies it gives
Connection dropped by server?

Related

Connect to database running in local from application running inside docker container

I am new to docker, attempting to connect oracle database running in local from an application running inside docker.
Getting below error:
IO Error: The Network Adapter could not establish the connection.
I browsed that we can pull oracle image and run in the docker container but I want to connect locally running database.
Can someone please guide me how to connect oracle database running in local windows machine from application inside docker container.
Code to get SessionFactory instance:
private SessionFactory getSessionFactory() {
SessionFactory sessionFactory = null;
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's
// properties
System.out.println("SessionFactory getting called");
Properties settings = new Properties();
settings.put(Environment.DRIVER, "oracle.jdbc.driver.OracleDriver");
settings.put(Environment.URL, "jdbc:oracle:thin:#localhost:1521:xxxxx");
settings.put(Environment.USER, "xxxxx");
settings.put(Environment.PASS, "xxxx");
settings.put(Environment.DIALECT, "org.hibernate.dialect.Oracle12cDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.C3P0_MIN_SIZE, 10);
settings.put(Environment.C3P0_MAX_SIZE, 100);
settings.put(Environment.C3P0_TIMEOUT, 300);
configuration.setProperties(settings);
configuration.addAnnotatedClass(SecretQuestionsEnity.class).addAnnotatedClass(CustomerEntity.class)
.addAnnotatedClass(AddressEntity.class).addAnnotatedClass(SecretAnswersEntity.class)
.addAnnotatedClass(BranchEntity.class).addAnnotatedClass(AccountEntity.class)
.addAnnotatedClass(CurrentACEntity.class).addAnnotatedClass(SavingsACEntity.class)
.addAnnotatedClass(TransactionEntity.class).addAnnotatedClass(PayeeEntity.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
Error :
2020-07-24 16:32:09 WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 17002, SQLState: 08006
2020-07-24 16:32:10 ERROR o.h.e.jdbc.spi.SqlExceptionHelper - IO Error: The Network Adapter could not establish the connection
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
If you are running an application inside docker container then the localhost refers to container not your local windows machine
settings.put(Environment.URL, "jdbc:oracle:thin:#localhost:1521:xxxxx");
Either you can give your windows machine IP address instead of localhost in the URL string or you can read it from environment variable by passing it in docker run command.

JavaMail API doesn't work for me with an exception com.sun.mail.util.MailConnectException: Couldn't connect to host, port

I've seen all questions and answers about this problem, I've read the FAQ, tried all solutions which I've found, except writing my own one, I've turned off less secure app Gmail and so on. I've checked telnet connection, of course, tried to ping smtp.gmail.com and everything works fine. Even I've written (to be sure) small application on C# which took me 5 minutes (and this one works!). Please give me a clue how can I solve this issue. For every solution using ttl or ssl I get this stacktrace
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at com.luga.culturalpickup.UsableSendMail.sendFromGMail(UsableSendMail.java:64)
at com.luga.culturalpickup.UsableSendMail.main(UsableSendMail.java:84)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:359)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 5 more
I've disabled firewall completely.
Even I've used some wrappers around JavaMail Api to send letters and internally they were falling with this exception!
I want to send small email using java!
for exmaple, this code produce error specified above
public class GoogleTest {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_PORT = "465";
private static final String emailMsgTxt = "Test Message Contents";
private static final String emailSubjectTxt = "A test from gmail";
private static final String emailFromAddress = "mail4#gmail.com";
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
private static final String[] sendTo = { "alex.95#mail.ru" };
public static void main(String args[]) throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully mail to All Users");
}
public void sendSSLMessage(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mail4#gmail.com", "password");
}
});
session.setDebug(debug);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}
I get following stacktrace
DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
Exception in thread "main" com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:267)
at javax.mail.Transport.send0(Transport.java:252)
at javax.mail.Transport.send(Transport.java:174)
at com.luga.culturalpickup.GoogleTest.sendSSLMessage(GoogleTest.java:72)
at com.luga.culturalpickup.GoogleTest.main(GoogleTest.java:29)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:359)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:217)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 8 more
The configuration details look OK to me.
The big clue is that you are getting "Connection refused". In theory, there are a few possible explanations for this:
The smtp.gmail.com servers are all down. This is highly unlikely.
The smtp.gmail.com servers may have black-listed your IP address or a network range containing your IP address. (Perhaps the gmail.com servers have been getting too much SPAM via your ISP.)
Maybe there is a country-wide block on emails. (For example, it has been claimed that China does this sometimes.)
Maybe ISP is blocking the connection to smtp.gmail.com on those ports ... or maybe all outbound connections on this ports. This may be done to prevent spamming by your ISP's customers. Check your ISP's terms and conditions regarding sending emails, and check for information on how you should do it.
Maybe your organization is blocking the connection to smtp.gmail.com. This could be done so that they can monitor all out-going emails. It could also be done to prevent spamming or behavior that could be interpreted as spamming. Check with your local IT and network managers.
Maybe it is your machine's internal firewall. (Though you say that you disabled it ...)
There is one simple test you can do to validate this. Use the "telnet" command to try to connect to smtp.gmail.com on those two ports. If you get a "Connection refused", it is strong evidence of some kind of blocking somewhere.
Finally, if the ports appear to be open, check what you are doing against this tutorial page:
https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
After one and a half of day I've found a problem. It was due to avg antivirus or to say it more correctly avg virus. It was turned off (as he has displayed me), but I've noticed some avg advertisment attached to messages sent with application written on C#, I've found a way to definitely turn it off. And it works now!

SSLHandshakeException: Remote host closed connection during handshake

I have the following method for retrieving messages from Gmail using imap
public static void main(String[] args)
{
Properties props = new Properties();
try
{
props.load(new FileInputStream(new File("smtp.properties")));
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("smtp.gmail.com", "******#gmail.com", "mypass");
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
int messageCount = inbox.getMessageCount();
Message[] messages = inbox.getMessages();
System.out.println("------------------------------");
for (int i = 0; i < 10; i++)
{
System.out.println("Mail Subject:- " + messages[i].getSubject());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
my smtp.properties contains
mail.smtp.host=smtp.gmail.com
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.auth=true
mail.smtp.port=465
I get the following when I run the program
javax.mail.MessagingException: Remote host closed connection during handshake;
nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:695)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at gmailsmpt.Main.main(Main.java:25)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:532)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:337)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:116)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:121)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:710)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:659)
... 3 more
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(Unknown Source)
... 14 more
How can I fix the issue?
First, clean up all these common mistakes. You don't need any socket factories.
Then try these connection debugging tips.
Possibly you have a firewall or anti-virus program that's preventing you from connecting.
The problem is that the default TLS version in JAVA jre1.8.0_141 1.0, however due to vulnerabilities in 1.0 a lot of email servers no longer accept connections. To instead use 1.2 directly in code this instruction worked for me when creating properties for sending mail:
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
For example:
Properties props = System.getProperties();
props.put("mail.smtp.host", mailHost);
props.put("mail.smtps.auth", mailAuth);
props.put("mail.transport.protocol", mailProtocol);
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
// Get a Session object
Session sess = Session.getInstance(props, null);
// construct the message
MimeMessage msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(mailUser));
Also note, you could just set that same property in the properties file you're loading (smtp.properties) at the start of your try block.
Are there more stacktraces? Older Java versions have problems with TLS handshakes with RSA keys with more than 1024 bit (may be also with keys having exactly bit byte).
This was fixed in Java 1.7 or Java 1.8.
try adding below to the properties:
properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");

MailConnectException while sending mail using java mail api

Trying to send an email using java mail api. And I keep getting MailConnectException. I have tried multiple ways to solve it without success.
Exception is thrown by this statement
transport.connect("smtp.gmail.com", "someone#gmail.com", "myPassword");
Can anyone tell me what I'm doing wrong?
public static void main(String[] args) {
String host = "smtp.gmail.com";
String from = "someone#gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "myPassword");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
try{
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, "someone#hotmail.com");
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", "someone#gmail.com", "myPassword");//CAUSES EXCEPTION
transport.sendMessage(message, message.getAllRecipients());
}catch(MessagingException e){
e.printStackTrace();
}
}
Stack trace:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1984)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at com.karmacrafts.util.CustomEmail.main(CustomEmail.java:127)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:301)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
... 4 more
This looks like network problem. Even though it could occur due to variety of reasons, like :-
"Couldn't connect to host, port" could be caused by wrong host name, wrong port, a blocking firewall (on the server, on gateways, even on your own machine), network failure, server downtime, etc.
Can you connect to the mail server using telnet ?
Also see this FAQ for some mistakes you committed http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes
Read this answer on how to send emails using gmail https://stackoverflow.com/a/47452/3107043
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
props.put("mail.smtp.port", "587"); transport.send(message);
After 8 hours of pain, I've solved this by turning off:
1) my windows firewall
2) my antivirus software
hope this helps
I met the same problem, and the reason is that I opened a vpn. Hope this will be helpful.
For me, de-activating firewall and anti-virus did not work.
I tried the alternate ports given in the mailtrap's SMTP settings
25 or 465 or 587 or 2525
changing spring.mail.port to 2525 in the applications.properties file worked for me
Open /etc/postfix/main.cf
Search /inet_interfaces line and comment localhost, un-comment all:
Restart the SMTP server using terminal command "postfix restart"

how to read email using java?

I can send email, but I am unable to read the emails.
Here is my code to connect to the mail server:
String host = "na-*****.*****.****.ea.com";
String username = "*****#*******.ea.com";
String password = "********";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
session.setDebug(true);
Store store = session.getStore("pop3");
store.connect(host, username, password);
Whenever I try to read email using the code,it throws the following error:
javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:210)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at DisplayMail.main(DisplayMail.java:18)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.readLine(Unknown Source)
at com.sun.mail.pop3.Protocol.readResponse(Protocol.java:683)
at com.sun.mail.pop3.Protocol.simpleCommand(Protocol.java:656)
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:109)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:261)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:206)
... 3 more
Can someone tell me what I'm doing incorrectly, or if more information is needed?
there are multiple email protocols (pop3, imap, exchange, etc) and depending on which protocol you want you will need to find a library (or roll your own) to speak the protocol of choice to access and download emails from a server.
I would suggest looking at the JavaMail API

Categories