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

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.

Related

JavaMail always uses localhost in Liferay

I am facing a strange problem and I can't figure out the problem. I have a web application/portlet deployed in Liferay portal which should be sending an email. I have the configuration correct and the code looks like this:
Session mailSession = mailSender.getSession();
Transport transport = mailSession.getTransport("smtp");
Message message = buildMessage(); // placeholder for building the message
try {
transport.sendMessage(msg, msg.getAllRecipients());
} finaly {
transport.close();
}
This, however, always tries to connecto to localhost:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
liferay_1 | nested exception is:
liferay_1 | java.net.ConnectException: Connection refused (Connection refused)
Now, I though that the connection settings are not correct, so I decided to log them:
LOG.debug("Host:" + mailSender.getHost() + " --- Port: " + mailSender.getPort());
LOG.debug("Password:" + mailSender.getPassword() + " --- User: " + mailSender.getUsername());
mailSession.getProperties().entrySet().forEach(p -> LOG.debug("---" + p.getKey() + "-" + p.getValue()));
And they are indeed correct in the session:
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:92) - Host:test-host --- Port: 5678
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:93) - Password:$test --- User: test
liferay_1 | DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.transport.protocol-smtp
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.debug-true
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.smtp.auth-test
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:97) - ---mail.smtp.starttls.enable-true
liferay_1 | DEBUG [http-nio-8080-exec-1] (MailSenderService:99) - Transport:smtp://liferay#
I can't figure out what else I can do and I don't know from where does the transport get localhost and port 25.
After further investigation, I discovered that there is a method for connecting to a specified host.
/**
* Similar to connect(host, user, password) except a specific port
* can be specified.
*
* #param host the host to connect to
* #param port the port to connect to (-1 means the default port)
* #param user the user name
* #param password this user's password
* #exception AuthenticationFailedException for authentication failures
* #exception MessagingException for other failures
* #exception IllegalStateException if the service is already connected
* #see #connect(java.lang.String, java.lang.String, java.lang.String)
* #see javax.mail.event.ConnectionEvent
*/
public synchronized void connect(String host, int port,
String user, String password) throws MessagingException
Using this one, you can specify the exact host, port and credentials. Why the Session does not contain this information and why it is not being used, even though the Transport and Session are obtained fro the original JavaMailSenderImpl is still a mystery to me.
What version of Liferay are you on?
First thing first, you will need to check if your credentials are correctly set up in Control Panel > Server Administration > Mail.
Check your:
Outgoing SMTP Server and
Outgoing Port
if they are still pointing to localhost and 25 respectively.
Second, the implementation looks unfamiliar to me. Can you try this way?
import com.liferay.mail.kernel.service.MailServiceUtil;
...
Message message = buildMessage();
MailServiceUtil.sendEmail(message);
or if you want to get a session
MailServiceUtil.getSession()

Problem at creating EMS application supporting Failover/FaultTolerance

I am starting to study how can I implement an application supporting Failover/FaultTolerance on top of JMS, more precisely EMS
I configured two EMS servers working both with FaultTolerance enabled:
For EMS running on server on server1 I have
in tibemsd.conf
ft_active = tcp://server2:7232
in factories.conf
[GenericConnectionFactory]
type = generic
url = tcp://server1:7232
[FTTopicConnectionFactory]
type = topic
url = tcp://server1:7232,tcp://server2:7232
[FTQueueConnectionFactory]
type = queue
url = tcp://server1:7232,tcp://server2:7232
And for EMS running on server on server2 I have
in tibemsd.conf
ft_active = tcp://server1:7232
in factories.conf
[GenericConnectionFactory]
type = generic
url = tcp://server2:7232
[FTTopicConnectionFactory]
type = topic
url = tcp://server2:7232,tcp://server1:7232
[FTQueueConnectionFactory]
type = queue
url = tcp://server2:7232,tcp://server1:7232
I am not a TIBCO EMS expert but my config seems to be good: When I start EMS on server1 I get:
$ tibemsd -config tibemsd.conf
...
2022-07-20 23:04:58.566 Server is active.
2022-07-20 23:05:18.563 Standby server 'SERVERNAME#server1' has connected.
then if I start EMS on server2, I get
$ tibemsd -config tibemsd.conf
...
2022-07-20 23:05:18.564 Accepting connections on tcp://server2:7232.
2022-07-20 23:05:18.564 Server is in standby state for 'tcp://server1:7232'
Moreover, if I kill active EMS on server1, I immediately get the following message on server2:
2022-07-20 23:21:52.891 Connection to active server 'tcp://server1:7232' has been lost.
2022-07-20 23:21:52.891 Server activating on failure of 'tcp://server1:7232'.
...
2022-07-20 23:21:52.924 Server is now active.
Until here, everything looks OK, active/standby EMS servers seems to be correctly configured
Things get more complicated when I write a piece of code how is supposed to connect to these EMS servers and to periodically publish messages. Let's try with the following code sample:
#Test
public void testEmsFailover() throws JMSException, InterruptedException {
int NB = 1000;
TibjmsConnectionFactory factory = new TibjmsConnectionFactory();
factory.setServerUrl("tcp://server1:7232,tcp://server2:7232");
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
connection.start();
for (int i = 0; i < NB; i++) {
LOG.info("sending message");
Queue queue = session.createQueue(QUEUE__CLIENT_TO_FRONTDOOR__CONNECTION_REQUEST);
MessageProducer producer = session.createProducer(queue);
MapMessage mapMessage = session.createMapMessage();
mapMessage.setStringProperty(PROPERTY__CLIENT_KIND, USER.toString());
mapMessage.setStringProperty(PROPERTY__CLIENT_NAME, "name");
producer.send(mapMessage);
LOG.info("done!");
Thread.sleep(1000);
}
}
If I run this code while both active and standby servers are up, everything looks good
23:26:32.431 [main] INFO JmsEndpointTest - sending message
23:26:32.458 [main] INFO JmsEndpointTest - done!
23:26:33.458 [main] INFO JmsEndpointTest - sending message
23:26:33.482 [main] INFO JmsEndpointTest - done!
Now If I kill the active EMS server, I would expect that
the standby server would instantaneously become the active one
my code would continue to publish such as if nothing had happened
However, in my code I get the following error:
javax.jms.JMSException: Connection is closed
at com.tibco.tibjms.TibjmsxLink.sendRequest(TibjmsxLink.java:307)
at com.tibco.tibjms.TibjmsxLink.sendRequestMsg(TibjmsxLink.java:261)
at com.tibco.tibjms.TibjmsxSessionImp._createProducer(TibjmsxSessionImp.java:1004)
at com.tibco.tibjms.TibjmsxSessionImp.createProducer(TibjmsxSessionImp.java:4854)
at JmsEndpointTest.testEmsFailover(JmsEndpointTest.java:103)
...
and in the logs of the server (the previous standby server supposed to be now the active one) I get
2022-07-20 23:32:44.447 [anonymous#cersei]: connect failed: server not in active state
2022-07-20 23:33:02.969 Connection to active server 'tcp://server2:7232' has been lost.
2022-07-20 23:33:02.969 Server activating on failure of 'tcp://server2:7232'.
2022-07-20 23:33:02.969 Server rereading configuration.
2022-07-20 23:33:02.971 Recovering state, please wait.
2022-07-20 23:33:02.980 Recovered 46 messages.
2022-07-20 23:33:02.980 Server is now active.
2022-07-20 23:33:03.545 [anonymous#cersei]: reconnect failed: connection unknown for id=8
2022-07-20 23:33:04.187 [anonymous#cersei]: reconnect failed: connection unknown for id=8
2022-07-20 23:33:04.855 [anonymous#cersei]: reconnect failed: connection unknown for id=8
2022-07-20 23:33:05.531 [anonymous#cersei]: reconnect failed: connection unknown for id=8
I would appreciate any help to enhance my code
Thank you
I think I found the origin of my problem:
according to the page Tibco-Ems Failover Issue, the error message
reconnect failed: connection unknown for id=8
means: "the store (ems db) was'nt share between the active and the standby node, so when the active ems failed, the new active ems was'nt able to recover connections and messages."
I realized that it is painful to configure a shared store. To avoid it, I configured two tibems on the same host, by following the page Step By Step How to Setup TIBCO EMS In Fault Tolerant Mode:
two tibemsd.conf configuration files
configure a different listen port in each file
configure ft_active with url of other server
configure factories.conf
By doing so, I can replay my test and it works as expected

Spring boot application return me : 550 Access denied - Invalid HELO name (See RFC2821 4.1.1.1)

while trying to send email via my spring boot application i got this error :
failures; nested exception is javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
java.net.SocketException: Software caused connection abort: socket write error. Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 550 Access denied - Invalid HELO name (See RFC2821 4.1.1.1);
nested exception is:
com.sun.mail.smtp.SMTPSenderFailedException: 550 Access denied - Invalid HELO name (See RFC2821 4.1.1.1)
My Spring boot application is generated with jhipster and here is my application-dev.yml config for mail config :
mail:
host: mail.example.com
port: 587
username: support#example.com
password: ************
NB : example.com is just an example for not sharing confidential data, my config is correct i have tested it with and working great but not on my spring boot application
I have provided a sample below.
Showing how I send emails with spring-boot
add the starter mail dependency in your pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Add the below bean in your Application class :
#Bean
public JavaMailSenderImpl customJavaMailSenderImpl(){
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(username);
mailSender.setPassword(password);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}
See an example, using the customJavaMailSenderImpl bean below :
#Service
public class emailSender{
#Autowired
JavaMailSenderImpl customJavaMailSenderImpl;
public void mailWithAttachment() throws Exception {
MimeMessage message = customJavaMailSenderImpl.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true,"utf-8");
helper.setTo("abc#example.com");
helper.setSubject("test");
helper.setText("hello test", true);
helper.setFrom("abd#example.com", "John Doe");
customJavaMailSenderImpl.send(message);
}
}
After review i found that i forgot to add some mail config in my application-dev.yml :
mail.smtp.starttls.enable : true and mail.smtp.starttls.auth : true
mail config should look like :
mail:
host: mail.example.com
port: 587
username: support#example.com
password: ************
properties:
mail:
smtp:
auth: true
starttls:
enable: true

Trouble with Glassfish Server and ActiveMQ: peer did not send his wire format

I'm getting this error while trying to set up a JMSPublisher and JMSSubscriber
jndi.properties
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
java.naming.provider.url = tcp://localhost:4848?wireFormat.maxInactivityDurationInitalDelay=30000
topic.topic/flightStatus = flightStatus
Glassfish server is running on: http://localhost:4848
Publisher:
JmsPublisher publisher= new JmsPublisher("ConnectionFactory", "topic/flightStatus");
...
public JmsPublisher(String factoryName, String topicName) throws JMSException, NamingException {
Context jndiContext = new InitialContext();
TopicConnectionFactory factory = (TopicConnectionFactory) jndiContext.lookup(factoryName);
Topic topic = (Topic) jndiContext.lookup(topicName);
this.connect = factory.createTopicConnection();
this.session = connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
this.publisher = session.createPublisher(topic);
}
Exception:
Exception in thread "main" javax.jms.JMSException: Wire format negotiation timeout: peer did not send his wire format.
at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:62)
at org.apache.activemq.ActiveMQConnection.syncSendPacket(ActiveMQConnection.java:1395)
at org.apache.activemq.ActiveMQConnection.ensureConnectionInfoSent(ActiveMQConnection.java:1481)
at org.apache.activemq.ActiveMQConnection.createSession(ActiveMQConnection.java:323)
at org.apache.activemq.ActiveMQConnection.createTopicSession(ActiveMQConnection.java:1112)
at com.mycompany.testejms.JmsPublisher.<init>(JmsPublisher.java:34)
at com.mycompany.testejms.JmsPublisher.main(JmsPublisher.java:51)
Caused by: java.io.IOException: Wire format negotiation timeout: peer did not send his wire format.
at org.apache.activemq.transport.WireFormatNegotiator.oneway(WireFormatNegotiator.java:98)
at org.apache.activemq.transport.MutexTransport.oneway(MutexTransport.java:68)
at org.apache.activemq.transport.ResponseCorrelator.asyncRequest(ResponseCorrelator.java:81)
at org.apache.activemq.transport.ResponseCorrelator.request(ResponseCorrelator.java:86)
at org.apache.activemq.ActiveMQConnection.syncSendPacket(ActiveMQConnection.java:1366)
... 5 more
The error indicates that the ActiveMQ client is not actually communicating with an ActiveMQ broker. Glassfish may be listening on http://localhost:4848, but apparently that's not where the ActiveMQ broker is listening for connections. From what I understand, port 4848 is where the Glassfish web admin console listens for connections. Note the http in the URL you provided. By default, ActiveMQ listens on port 61616.

Java spring boot - JavaMailSender errors

I am fairly new to Java spring - I am getting the following errors when trying to send a test email.
Error in sending email:
org.springframework.mail.MailSendException: Mail server connection
failed; nested exception is javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?. Failed messages: javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?; message exceptions (1) are:
Failed message 1: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?"
SimepleEmailController.java
package controller;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class SimpleEmailController {
#Autowired
private JavaMailSender sender;
#RequestMapping("/simpleemail")
#ResponseBody
String home() {
try {
sendEmail();
return "Email Sent!";
}catch(Exception ex) {
return "Error in sending email: "+ex;
}
}
private void sendEmail() throws Exception{
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("set-your-recipient-email-here#gmail.com");
helper.setText("How are you?");
helper.setSubject("Hi");
sender.send(message);
}
}
The application.properties settings are as follows - testing on a test account
spring.mail.port=587
spring.mail.host=smtp.gmail.com
spring.mail.username=xxxxxxxxxxxxx#gmail.com
spring.mail.password=zzzzzzzzzzz
spring.mail.protocol=smtp
spring.mail.defaultEncoding=UTF-8
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.socketFactory.port = 25
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = true
spring.mail.properties.mail.smtp.ssl.enable=true
support.mail.address=xxxxxxxxxxxxxxx#gmail.com
Remove this line from your application.properties:
spring.mail.properties.mail.smtp.ssl.enable=true
Since your are using port 587 which is for sending message with TLS. You should use above configuration if you are using port 465 which is a SMTP SSL port.
Try to use your # as setTo() param for a first quick test.
Then, you can let default configuration, you don't need much of it.
spring.mail.host=smtp.gmail.com
spring.mail.username=romanineers#gmail.com
spring.mail.password=****** #hope it wasn't your real password :)
spring.mail.properties.mail.smtp.auth = true
As per the error you are getting, just set spring.mail.properties.mail.smtp.ssl.enable=true
property value to false and try.
Problem fixed --- javax.mail.AuthenticationFailedException is thrown while sending email in java -- have to configure the gmail to allow less secure apps --
spring.mail.port=465
spring.mail.host=smtp.gmail.com
spring.mail.username=xx#gmail.com
spring.mail.password=yyyyy
spring.mail.protocol=smtp
spring.mail.defaultEncoding=UTF-8
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
spring.mail.properties.mail.smtp.ssl.enable=false
support.mail.address=xx#gmail.com

Categories

Resources