I have tried to troubleshoot this issue a lot and now as a last resort posting it here. Please help me!
Issue: I am able to send mail by calling the class from a main method. When I try to call the same class from a Struts2 Action class it does not send an email, rather gives the below error. I am using Jboss EAP 7.0.0.Alpha1. I think the issue might be lying in the JBoss configuration. I have also changed the Standalone-full.xml file.(To note I am using standalone-full.xml and my other web components are working fine).
I did run it in debug mode and saw all values are getting populated. When we run it from the struts2 action class it does not send the message.
Changes made to Standalone-full.xml:
<mail-session name="java:jboss/mail/Default"
from="somedummyuser#gmail.com" jndi-
name="java:jboss/mail/Default">
<smtp-server password="******" username="somedummyuser"
ssl="true" outbound-socket-binding-ref="mail-smtp"/>
</mail-session>
</subsystem>
<outbound-socket-binding name="mail-smtp">
<remote-destination host="smtp.gmail.com" port="465"/>
</outbound-socket-binding>
Java Code:
public class SendEmail {
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String from, String to, String subject, String
msg)
throws Exception,NamingException{
//creating message
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(msg);
//sending message
System.out.println("SimpleMailMessage object:"+simpleMailMessage);
mailSender.send(simpleMailMessage);
}
}
Class with MainMethod Which is executing the above code findE and sending the email successfully:
public class MainMethod_SendEmail {
public static void main(String[] args) throws Exception{
Resource r=new ClassPathResource("webApplicationContext.xml");
BeanFactory b=new XmlBeanFactory(r);
SendEmail m=(SendEmail)b.getBean("sendEmail");
String sender = AccessPropertiesUtil.getInstance().getProperty("from");
String receiver = AccessPropertiesUtil.getInstance().getProperty("to");
String subject =
AccessPropertiesUtil.getInstance().getProperty("subject");
String message =
AccessPropertiesUtil.getInstance().getProperty("message");
m.sendMail(sender, receiver, subject, message);
System.out.println("success");
}
}
But the same mail sending code is not getting executed from a Struts2 Action class:
Struts2Action Class:
public String execute()
{
emailSending();
}
private void emailSending() throws Exception
{
System.out.println("Sending Email");
String sender =
AccessPropertiesUtil.getInstance().getProperty("from");
String receiver =
AccessPropertiesUtil.getInstance().getProperty("to");
String subject =
AccessPropertiesUtil.getInstance().getProperty("subject");
String message =
AccessPropertiesUtil.getInstance().getProperty("message");
sendEmail.sendMail(sender, receiver, subject, message);
}
Error Trace:
org.springframework.mail.MailSendException: Mail server connection
failed;
nested exception is javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 465, response: -1. Failed
messages: javax.mail.MessagingException: Could not connect to SMTP
host: smtp.gmail.com, port: 465, response: -1; message exception details
(1) are:
2016-07-13 02:45:33 ERROR stderr:71 - Failed message 1:
2016-07-13 02:45:33 ERROR stderr:71 - javax.mail.MessagingException:
Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
2016-07-13 02:45:33 ERROR stderr:71 - at
com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2042)
2016-07-13 02:45:33 ERROR stderr:71 - at
com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
2016-07-13 02:45:33 ERROR stderr:71 - at
javax.mail.Service.connect(Service.java:364)
Related
I am trying to call some external API hosted on azure from my web Api. The API is working fine on my local machine but when I deploy it IIS on server it starts throwing System.Net.Sockets.SocketException (10060).A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. Although I have increased the request timeout to 5 minutes but connection is silently stopping after 21 seconds and throwing aforementioned exception.
Here is my code:
var telemetries = new TelemetryResponse();
var client = httpClientFactory.CreateClient("Lynx");
client.Timeout = TimeSpan.FromMinutes(5);
var httpResponseMessage = await client.GetAsync("vehicletelemetries/All?key=iLJIbAVXOnpKz5xyF0zV44yepu5OVfmZFhkHM7x");
if (httpResponseMessage.IsSuccessStatusCode)
{
string content = await httpResponseMessage.Content.ReadAsStringAsync();
telemetries = JsonConvert.DeserializeObject<TelemetryResponse>(content);
}
Exception I am getting is:
System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
at System.Net.Sockets.Socket.g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken)
You got an error code:
WSAETIMEDOUT
10060
Connection timed out.
A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.
https://learn.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2#WSAETIMEDOUT
Check your network connection, ip adress, port and maybe the connection got blocked from a firewall.
Hi guys the culprit was the proxy and we have to configure our HttpClient with proxy while creating it/registering in the DI container. I have registered the HttpClient in DI like this.
var proxySettings = new ProxySetting();
Configuration.Bind(nameof(ProxySetting), proxySettings);
services.AddHttpClient("Lynx", client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("LynxUrl").Value);
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new MyProxy(proxySettings)});
And my proxy code is
public class MyProxy : IWebProxy
{
private readonly ProxySetting _proxySetting;
public MyProxy(ProxySetting proxySetting)
{
_proxySetting = proxySetting;
}
public ICredentials Credentials
{
//get { return new NetworkCredential("username", "password"); }
get { return new NetworkCredential(_proxySetting.UserName, _proxySetting.Password,_proxySetting.Domain); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri(_proxySetting.ProxyUrl);
}
public bool IsBypassed(Uri host)
{
return false;
}
}
It has resolved my problem completely.
Exception while connecting to the server: A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond.
1.) able to ping the server
2.) telnet smtp.office365.com 587 respond as expected.
public ConnectSmtpServer()
{
using MailKit.Net.Smtp;
string _SmtpServer = "smtp.office365.com";
int _portNumber = 587;
Console.WriteLine("Welcome!");
using (SmtpClient smtp = new SmtpClient())
{
try
{
smtp.Timeout = 30 * 1000;
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine("Test smtp connection using MailKit.Net !");
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine();
}
}
}
I am getting the following error when setting up an email service with spring boot while trying to connect to round cube:
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
This leads me to think roundcude is not using a SSL connection and I should not use port 143. Therefore I try and use port 25, but I get the following error when I do.
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
application.properties
#email setup
spring.mail.host = mail.email address.com
spring.mail.username = email address
spring.mail.password = my password
spring.mail.properties.mail.smtp.auth= true
spring.mail.port = 25 or port 145
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 = true
Email service
#Component
public class EmailServiceImpl implements EmailService {
#Autowired
private JavaMailSender javaMailSender;
#Override
public void sendEmail(String toAddress, String fromAddress,
String subject, String body) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(fromAddress);
simpleMailMessage.setTo(toAddress);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(body);
javaMailSender.send(simpleMailMessage);
}
}
I looked at roundcube's documentation and apparently is uses port 143 so this is rather confusing. This making me think I am setting this up wrong.
I also tried gmail but since I have a two factor authentication I ran into more issue so I decided to use roundcube which is what I would rather use anyway.
Advice?
It seems you're trying to connect to SMTP using non-secure ports. Usually secure ports would be 587 or 465.
This is the configuration that works for me to send e-mail using GMail:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=my-email#gmail.com
spring.mail.password=my-password
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.connectiontimeout = 60000
spring.mail.properties.mail.smtp.timeout = 60000
I have a method that sends many emails to exchange server over smtp using JavaMail, below is my code,
public void sendMail(){
final String host="host",port="587",username="mail1#local.local",password="password",from="";
try {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.ssl.trust", host);
final String email = from;
Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
Session session = Session.getInstance(props,authenticator);
InternetAddress replyToAddress [] = new InternetAddress[1];
replyToAddress[0] = new InternetAddress("mail1#local.local");
Transport transport = session.getTransport("smtp");
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("mail1#local.local"));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("mail2#local.local"));
mimeMessage.setSubject("Test");
mimeMessage.setText("Hello Testing");
mimeMessage.setReplyTo(replyToAddress);
transport.send(mimeMessage);
System.out.println("Email has been Sent Successfully to");
} catch (MessagingException e) {
e.printStackTrace();
}
Now when I apply a loop and call this function 10 times then only first five emails are sent successfully, for rest of the request I get the following exception,
javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
java.net.SocketException: Connection closed by remote host
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2157)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2144)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1210)
at javax.mail.Transport.send0(Transport.java:197)
at javax.mail.Transport.send(Transport.java:124)
if I increase the request count then still only first five emails are sent, rest of them throws the exception.
If I put the failed request in some queue and retry them later then some of them will be sent.
Any clue will be appreciated, do I need to check for some configuration on Exchange server?
We have seen this exact same issue with a MS Exchange Server 2010. We had to increase the ReceiveConnector message rate limit by issuing the following Powershell-command:
Set-ReceiveConnector "Client CLIENTNAME" -MessageRateLimit unlimited
I'm having a trouble sending an email using Google's SMTP Server. I've looked for a solution but i have not found one. So here's the code.
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
...
...
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
Properties props = new Properties();
props.put("true", "mail.smtp.auth");
props.put("true","mail.smtp.starttls.enable");
props.put("smtp.gmail.com", "mail.smtp.host");
props.put("587", "mail.smtp.port");
Session sess=Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("myemail#gmail.com", "mypassword");
}
}
);
try{
Message message= new MimeMessage(sess);
message.setFrom(new InternetAddress("myemail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("myemail#gmail.com"));
message.setSubject("message");
message.setText("text");
Transport.send(message);
JOptionPane.showMessageDialog(null, "Sent!");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
Each time when i press the button, it show me this error:
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
I've tried 3 ports: 25, 465, 587 , but it always gives me that error. I even made new rules for the port 25 to the firewall settings, but that doesn't seem to do the trick. Any thoughts what am i doing wrong? Could hibernate cause the problem? Because i'm using it in this project. Plus, i have installed mysql.
Your program is trying to connect to a local port, that's why it failed. If your listing is real code, you got the key and value backwards in the props.set statements.