SMTP TLS does not work for gmail - java

I would like to write a program which connects with the gmail server using SMTP TLS. I am using the code mentioned on this page :
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
I am getting connection time out exception. I can succefully send email if I use SMTP SSL.
public void sendUsingSMTP_TLS() {
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("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
I get following exception:
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException:
Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at SMTP_TLS.main(SMTP_TLS.java:48)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
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:253)
at javax.mail.Transport.send(Transport.java:124)
at SMTP_TLS.main(SMTP_TLS.java:43)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:299)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
… 7 more

The exception means that you are unable to connect to port 587 on server smtp.gmail.com . Verify this using telnet:
telnet smtp.gmail.com 587
(This works for me, so the server and port number are correct.)
Possible reasons for this to do not work from your location are:
Misconfigured proxy settings in Java
A firewall at your location, which forbids to connect to this port number.
If the telnet command above can connect, then you can rule out a problem with the firewall. But if it does not work and you are in a company network, then it's most likely the firewall which causes the problem.
Also, find out the port number which is used with your other connection method. Maybe that also works with TLS.

Related

javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate

I know there is several issue created about this error but nothing was helpful for me. I have method which is sending email with attachment on gmail server and it works fine. yesterday I bought a new mac mini m1. I tried this method to send email but it's throwing this error
public static void sentEmail(String report){
BaseTest base = new BaseTest();
String to = base.getProps().getProperty("emailTO"); ;//change accordingly
final String user = base.getProps().getProperty("emailFROM");//change accordingly
final String password = base.getProps().getProperty("emailPassword");//change accordingly
//1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("From Mobile Automation Project ");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("Report");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = report;//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("Report has been sent to: "+ to);
}catch (MessagingException ex) {ex.printStackTrace();}
}
Exception
javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
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)
at com.qa.utils.TestUtils.SendEmailTLS(TestUtils.java:228)
at com.qa.BaseTest.afterSuite(BaseTest.java:153)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:63)
at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:348)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:302)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:351)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:284)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:119)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:428)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)
at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:562)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:548)
Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
at sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:171)
at sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:101)
at sun.security.ssl.TransportContext.kickstart(TransportContext.java:238)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:394)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:373)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:486)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1902)
... 31 more
I changed this parameter
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
To this
properties.setProperty("mail.smtp.ssl.trust", "smtp.gmail.com");
But then I'm getting this exception
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 587;
nested exception is:
java.net.ConnectException: Connection refused (Connection refused)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
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)
at com.qa.utils.TestUtils.sentEmail(TestUtils.java:189)
at com.qa.BaseTest.afterSuite(BaseTest.java:152)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:63)
at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:348)
at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:302)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:351)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:284)
at org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75)
at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:119)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:428)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:162)
at org.apache.maven.surefire.booter.ForkedBooter.run(ForkedBooter.java:562)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:548)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:476)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:218)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:394)
at java.net.Socket.connect(Socket.java:606)
at java.net.Socket.connect(Socket.java:555)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
... 31 more
I had a similar issue and it seems to be related to Deepak's response. Following these instructions solved the problem.
It seems to be necessary to explicitly set required flag and the protocols:
Adding the following settings worked for me:
properties.put("mail.smtp.starttls.required", "true");
properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
I have to add that I tested this on port 465 and the full configuration looks like this
properies.put("mail.smtp.host", "smtp.gmail.com");
properies.put("mail.smtp.port", "465");
properies.put("mail.smtp.auth", "true");
properies.put("mail.smtp.starttls.enable", "true");
properies.put("mail.smtp.starttls.required", "true");
properies.put("mail.smtp.ssl.protocols", "TLSv1.2");
properies.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Warning do this own risk of enabling tlsv1 and tlsv1.1:
find the directory where java.security file saved.
in the case of ubuntu:
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security
find jdk.tls.disabledAlgorithms
remove TLSv1, TLSv1.1
reboot the server and run the project to try to send mail again.
To solve that issue, just upgrade the java library used to sendmail.
It worked for me.
I upgraded my javax.mail to 1.6.2 and solved the problem
I faced this issue due to older version of mysql-connector-java-5.1.40-bin.jar
Upgrading to 5.1.49 version solved my issue

MailConnectException: Couldn't connect to host, port: smtp.sendgrid.net

I have created API key for sendGrid:
I have following spring mail configuration:
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.sendgrid.net
spring.mail.username=apikey
spring.mail.password=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
spring.mail.port=25
spring.mail.protocol=smtp
spring.mail.test-connection=true
And I have following code:
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
Template template = freemarkerConfig.getTemplate(templateFileName);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, props);
helper.setTo("myEmail#gmail.com");
helper.setText(html, true);
helper.setSubject(subject);
helper.setFrom(from);
sender.send(message);
logger.debug("Send email to {} with subject: [{}]", Arrays.toString(to), subject);
Then I try to start application and experience following error:
27.01.18 20:07:20.460 [main] WARN c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.sendgrid.net, 25; timeout -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2118)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)
How can I fix this?
P.S.
Everything correct for port 587
But I want to use ssl and set port=465
spring.mail.port=465
And at this case my application freezes on startup.and after 5 min prints:
27.01.18 21:06:05.960 [main] WARN c.d.m.s.c.MailSenderValidatorAutoConfiguration - Mail server is not available
javax.mail.MessagingException: Could not connect to SMTP host: smtp.sendgrid.net, port: 465, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2106)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:712)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.testConnection(JavaMailSenderImpl.java:382)
How can I avoid this?
I used the port 2525 (Non-privileged) instead of 578 (privileged) to solve the problem locally. I can still use the privileged one on the cloud. That solved my problem.
You may need add something like this to your configuration.
spring.mail.smtp.ssl.enable=true
There is a probability that SendGrid SMTP servers are not discoverable in your country. try a proxy or VPN.

Unable to read Email using IMAP in JAVA.

I am trying to read email from Mail Server using JAVA. I've used IMAP protocol for that.
Everytime when I send request to read an email it throws me exception saying: javax.mail.MessagingException: Unrecognized SSL message, plaintext connection?
Here's my Code;
public void readEmail() throws Exception {
sessionIMAP = setupImap();
Store store = sessionIMAP.getStore("imap");
store.connect("localhost", 1143, "username", "password");
if (store.isConnected()) {
System.out.println("IMAP is connected");
} else {
System.out.println("IMAP is not connected");
}
}
private Session setupImap() {
System.out.println("in setupImap");
Session session1;
Properties props = new Properties();
props.put("mail.imap.starttls.enable", "true");
//props.put("mail.imaps.ssl.enable", "true");
//props.put("mail.imaps.auth", "true");
//props.put("mail.imaps.ssl.trust", "*");
props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.imap.socketFactory.fallback", "false");
props.put("mail.imap.host", "localhost");
props.put("mail.imap.port", 1143);
props.put("mail.imap.socketFactory.port", 1143);
props.setProperty("mail.store.protocol", "imap");
props.put("mail.debug", "true");
//props.put("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");
session1 = Session.getInstance(props, null);
//setupIMAPMsgTypeSetupForReportedIssue();
return session1;
}
Here's the full Exception I am getting:
DEBUG: JavaMail version 1.4.6
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,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
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: enable STARTTLS
DEBUG IMAP: trying to connect to host "localhost", port 1143, isSSL false
Invalid Args: read_Email
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.thalesifec.framework.tool.support.FwkAnnotatedTools$FwkToolClassInfo.execute(FwkAnnotatedTools.java:103)
at com.thalesifec.framework.tool.support.interactive.ConsoleInterface.handleToolSelected(ConsoleInterface.java:217)
at com.thalesifec.framework.tool.support.interactive.ConsoleInterface.interactiveCommandLoop(ConsoleInterface.java:113)
at com.thalesifec.framework.tool.support.interactive.ConsoleInterface.noArgsStart(ConsoleInterface.java:271)
at com.thalesifec.framework.tool.support.interactive.ConsoleInterface.delegateCommand(ConsoleInterface.java:295)
at com.thalesifec.framework.connectivitymanager.simulator.Main.main(Main.java:28)
Caused by: javax.mail.MessagingException: Unrecognized SSL message, plaintext connection?;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at com.thalesifec.framework.connectivitymanager.simulator.plugins.EMBATLTestTool.readEmail(EMBATLTestTool.java:136)
... 10 more
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:710)
at sun.security.ssl.InputRecord.read(InputRecord.java:527)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:211)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:116)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:115)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:685)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:636)
... 12 more
Could you please let me know what I am doing wrong?
Thanks in Advance
I commented out below line from the code and it worked!
props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Thank You

android sending email from app no longer working

I used this tutorial to send emails from inside my app.
I used the same code to 3 different apps and it all worked well. But now, a few months later, it stopped working.
I have searched all the possible sites, but none of them helped me.
I tried setting a lower security from my Gmail account and also changing the properties for my session, but nothing worked.
I would really appreciate some help.
Log.d("EmailSender","sending message");
Properties props = new Properties();
props.put("mail.smtp.host", host);
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,pass);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SharedPreferenceUtils.getUserEmail(getActivity())));
message.setSubject(subject);
message.setContent(content, "text/html; charset=utf-8");
//Transport.send(message);
Transport transport = session.getTransport("smtps");
transport.connect (host, Integer.parseInt(port), user, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Log.d("EmailSender", "message sent");
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
My error:
java.net.ConnectException: failed to connect to smtp.gmail.com/2a00:1450:4013:c01::6d (port 465) after 90000ms: isConnected failed: ENETUNREACH (Network is unreachable)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:288)
at com.mihaela.myapp.ui.dialog.EnterPasswordDialog$SendMailTask.doInBackground(EnterPasswordDialog.java:222)
at com.mihaela.myapp.ui.dialog.EnterPasswordDialog$SendMailTask.doInBackground(EnterPasswordDialog.java:179)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.net.ConnectException: failed to connect to smtp.gmail.com/2a00:1450:4013:c01::6d (port 465) after 90000ms: isConnected failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.isConnected(IoBridge.java:267)
at libcore.io.IoBridge.connectErrno(IoBridge.java:191)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:461)
at java.net.Socket.connect(Socket.java:918)
at java.net.Socket.connect(Socket.java:844)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 10 more
Caused by: android.system.ErrnoException: isConnected failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.isConnected(IoBridge.java:252)
... 19 more
From the logs:
java.net.ConnectException: failed to connect to smtp.gmail.com/2a00:1450:4013:c01::6d (port 465) after 90000ms: isConnected failed: ENETUNREACH (Network is unreachable)
Network is unreachable. The code looks okay, therefore the issue must be with the network. Please check your connectivity. Possible causes could be:
Very slow/ bad network. Try changing the network.
Internet permission not available in the manifest (this shouldn't be the case as described by your problem). Add the permission.
For future, you can add a network-check before sending network requests. This thread has some good answers for checking the network connectivity: How to check internet access on Android? InetAddress never times out

Java email - Exception Server is not trusted

I'm using apache commons mail to send emails. Unfortunately I'm getting following Exception:
org.apache.commons.mail.EmailException: Sending the email to the following server failed : mail.xxx.com:25
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
at org.apache.commons.mail.Email.send(Email.java:1267)
at com.xxx.UserBean.sendMail(UserBean.java:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
.
.
.
Caused by: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
java.io.IOException: Server is not trusted: mail.xxx.com
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1880)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:648)
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)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
... 85 more
Caused by: java.io.IOException: Server is not trusted: mail.xxx.com
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:443)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1875)
... 92 more
And here is my java code:
public void sendMail(){
try {
SimpleEmail mail = new SimpleEmail();
mail.setTLS(true);
mail.setAuthenticator(new DefaultAuthenticator("user","xyxyxyxy"));
mail.setHostName("mail.xxx.com");
mail.getMailSession().getProperties().put("mail.smtps.auth", true);
mail.getMailSession().getProperties().put("mail.debug", true);
mail.getMailSession().getProperties().put("mail.smtps.port", "587");
mail.getMailSession().getProperties().put("mail.smtp.starttls.enable", true);
mail.getMailSession().getProperties().put("mail.smtp.ssl.trust", "smtpserver");
mail.addTo("user#server.com", "user");
mail.setFrom("info#xxx.com");
mail.setSubject("Bla Bla");
mail.setMsg("Bla Bla again");
mail.send();
} catch (Exception ex) {
logger.info("Senden der Email ist gescheitert!", ex);
}
}
I've already read many threads and tried many hints. I'm stuck here!
I should mention that I'm able to send emails with another method using "javax.mail". But I'd like to move to apache.
I'm thankful for any help.
setTLS (Transport layer security) to false. If you are not using. When it is true its expected to be mail.xxx.com trusted server.
mail.setTLS(false);
Finally Solved. I tried everything to get authenticated at my exchange server.
use the code below:
Properties props = (Properties)System.getProperties().clone();
props.put("mail.smtp.host", host);
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.auth", true);
//Bypass the SSL authentication
props.put("mail.smtp.ssl.enable", false);
props.put("mail.smtp.starttls.enable", false);
If you're using Spring-Boot-Mail, try adding this line to you .properties file:
spring.mail.properties.mail.smtp.ssl.trust=smtp.mandrillapp.com

Categories

Resources