Spring Mail. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake - jakarta-mail

I connect to mail server on protocol smtp on port without encryption.
I get error
"Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS;\n nested exception is:\n\tjavax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;\n nested exception is:\n\tjavax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake"
My bean's config
#Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
javaMailSender.setProtocol(protocol);
javaMailSender.setUsername(from);
javaMailSender.setPassword(password);
javaMailSender.setPort(port);
javaMailSender.setDefaultEncoding(encoding);
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.smtp.starttls.enable", "true");
javaMailProperties.put("mail.smtp.auth", "true");
javaMailProperties.put("mail.transport.protocol", "smtp");
javaMailProperties.put("mail.debug", "true");
javaMailProperties.put("mail.smtp.localhost", "127.0.0.1");
javaMailProperties.put("mail.smtp.ssl.trust", "*");
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
javaMailSender.setJavaMailProperties(javaMailProperties);
return javaMailSender;
}
I can say one before it worked. What can be wrong?

Need to remove javaMailProperties.put("mail.smtp.starttls.enable", "true");

There may be a disagreement about which TLS versions or cipher suites are supported by both client and server. If you upgraded the JDK, for example, that might've changed. The https.protocols property isn't used by JavaMail, but if you need to set that for other reasons you may need to set the corresponding JavaMail property, e.g., mail.smtp.ssl.protocols.
You might need to follow the debugging tips in SSLNOTES.txt to find out exactly what's wrong.

Related

Jakarta Mail OAUTH support for Office365 over POP protocol

We are trying to connect to Office365 over POP3 using OAUTH. We get the error "Protocol error. Connection is closed. 10" stacktrace mentioned below
javax.mail.AuthenticationFailedException: Protocol error. Connection is closed. 10
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:193)
at javax.mail.Service.connect(Service.java:342)
Below if the snipped of code we are usign to connect
Properties props = new Properties();
props.put("mail.pop3.ssl.enable", "true");
props.put("mail.pop3s.auth.mechanisms","XOAUTH2");
props.put("mail.debug", "true");
session = Session.getInstance(props);
final Store store = session.getStore("pop3s");
store.connect("outlook.office365.com", 995, userId, accessToken);
We are able to connect to Office using IMAP protocol over OAUTH. we tried this with jakarta-mail-1.6.5 and jakarta-mail-1.6.6 both but are unable to resolve the error. Please suggest if we are connecting wrongly or there is any properties missing.
Worked with the workaround mentioned in https://github.com/eclipse-ee4j/mail/issues/461 on Jakarta-mail 1.6.6 development version.

Mail sending without authentication using Java Mail Api

I am following code to send mail without authentication.The java code described as follows.
final String frommail = "a#g.com"
String toEmail = "b#gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", PropertiesLoader.getPropertiesValue(MAIL_SMTP_AUTH));
props.put("mail.smtp.host", PropertiesLoader.getPropertiesValue(MAIL_SMTP_HOST));
props.put("mail.smtp.port", PropertiesLoader.getPropertiesValue(MAIL_SMTP_PORT));
//enable authentication
props.put(MAIL_SMTP_ENABLE, PropertiesLoader.getPropertiesValue(MAIL_SMTP_ENABLE));
Session session = Session.getInstance(props);
try {
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(frommail, EMAIL_FROM_NAME));
// msg.setReplyTo(InternetAddress.parse(frommail, false));
msg.setSubject(subject, "UTF-8");
msg.setContent(body, MAIL_CONTENT_TYPE);
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("pramilkprince#rediffmail.com", false));
Transport.send(msg);
logger.info("EMail Sent Successfully!!");
But when sending mail, it throws following exception
com.sun.mail.smtp.SMTPAddressFailedException: 554 5.7.1
: Relay access denied at
com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1862) at
com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1118)
at javax.mail.Transport.send0(Transport.java:254) at
javax.mail.Transport.send(Transport.java:124) at
com.gtl.gcc.util.SendEmail.sendEmailFromInfo(SendEmail.java:195) at
com.gtl.gcc.util.SendEmail.createMailBodyAndSendMailForUpdateKYC(SendEmail.java:144)
if any one have any idea about this please help
If you want to send mail without authentication, you need to run your own SMTP server. If it's on the public internet, it will be flooded with spam before you can use it yourself. If it's on your private intranet, you can make it work. Gmail, for example, is definitely not going to let you send mail without authenticating. Note that this has absolutely nothing at all to do with use of the JavaMail API.
As #BillShannon pointed out, sending through most SMTP servers will require authentication due to SPAM issues.
However, the MX Gateways for any domain are required to be open on TCP 25 and for emails without authentication.
While working on Java send email avoiding smtp relay server and send directly to MX server I created a small example to use the target domain's MX server to directly address that.
As pointed out before: If your sending server does not reverse-DNS to the domain you're sending from, you'll most likely end up being blocked or directly classified as spam.
Good Luck

Use Google hosted email to send email from dotnetnuke site hosted on hostgator

I am attempting to configure our dotnetnuke site to be able to send basic messages (things like lost password, newsletters, etc) to our users.
According to all the documentation I have found I have set up the site correctly
SMTP Server and port:smtp.gmail.com:587
Connection Limit:1
Max Idle Time:0
SMTP Authentication:Basic
SMTP Username:username#weburl.com
SMTP Password:password
I also created a smtp relay in google apps with comprehensive mail storage.
Is there something I am missing?
Below is the error message I receive from logs, if I understand what I am seeing this is the hosting service I am using correct?
2014-10-21 19:20:54,310 [PSS16][Thread:16][ERROR] DotNetNuke.Services.Exceptions.Exceptions - System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions 74.125.198.109:587
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at DotNetNuke.Services.Mail.Mail.SendMailInternal(MailMessage mailMessage, String subject, String body, MailPriority priority, MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable`1 attachments, String smtpServer, String smtpAuthentication, String smtpUsername, String smtpPassword, Boolean smtpEnableSSL)
I have my settings at:
smtp.gmail.com:587
1
0
Basic
SSL Enabled
username
password
That seems to work fine for my sites using Google's mail services.
It sounds like you need to setup a SMTP relay service. To confirm, you've configured the SMTP relay service as per this, correct?
If you've done everything there, then it's likely a connection configuration issue on your server. Although there's no specific settings mentioned for your provider, it looks like you should be using the FQDN, smtp-relay.gmail.com:587, rather than smtp.gmail.com:587.
Hope this helps!
Are you allowed to open up sockets from your environment? It looks like it might be an OS restriction for the process. Do you have shell access to the machine where this deployment is running?
Login, and see if you can open a connection (telnet) to the host and port you're trying to connect to. Don't look for any usable output, since it's expected to start a SSL handshake. Look for 'connection established' or some other message that indicates a tcp connection is open.

Getting javax.mail.MessagingException:Connection reset while trying to connect to MS exchange server using IMAP

I'm trying to connect to Microsoft Exchange server using Javamail. I have used IMAP protocol and port 443 is enabled to listen on exchange server side. I'm getting "javax.mail.MessagingException:Connection reset" error. I'm using javamail 1.4.7 Please help..
Properties prop = new Properties();
prop.setProperty("mail.imap.starttls.enable", "false");
// Use SSL
prop.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.imap.socketFactory.fallback", "false");
// Use port 443
prop.setProperty("mail.imap.port", "443");
prop.setProperty("mail.imap.socketFactory.port", "443");
prop.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");
Session session = Session.getDefaultInstance(prop);
Store store = session.getStore("imaps");
store.connect(hostname,username, password);
Port 443 is the https port, not the imaps port.
If you want to use the standard IMAP-over-SSL port, just use the "imaps" protocol and let JavaMail use the default port.
Also, see the JavaMail FAQ for some common mistakes in your code.
Thanks a lot for your suggestions..Yes indeed it was problem with the port. As suggested, I modified my code as below and it works fine now.
Properties prop = new Properties();
//Use SSL
prop.setProperty("mail.smtp.ssl.enable",true);
Session session = Session.getInstance(prop);
Store store = session.getStore("imaps");
store.connect(hostname,username, password);

smtp server to use for sending email through java mail api

I am using java mail api to send email and I need to know the parameters to use for sending a test email in development environment
If I want to use smtp.gmail.com as the smtp mail server , it has port 465 - found on internet , do I need to set authentication to true with username and password also set or authentication=false in fine?
also if authentication=true is required then username, password are my gmail username & password?
Also how to set the cc and bcc addresses in the email message?
Looking for the most basic way to send email to start with
Thanks
If you want to use Gmail, see the JavaMail FAQ.
In order to use gmail as your email server, you have to set a few properties like host,port,authentication etc as per JavaMail API standards. You can get these details from
https://support.google.com/a/answer/176600?hl=en
Sample Code:
public class SendMail
{
public SendMail()
{
// mail properties outgoing server (gmail.com)
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
//Create session object
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props,auth);
//prepare mail msg
MimeMessage msg = new MimeMessage(session);
//set header values
msg.setSubject("open to it know it1");
msg.setFrom(new InternetAddress("yyyyyy#gmail.com"));
//Here in below line, you can specify RecipientType as TO/CC/BCC as per your requirement
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("xxxxxxx#gmail.com"));
//msg text
msg.setText("mail from HCL Technlogies");
Transport.send(msg);
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("nitraja2015#gmail.com","raryan500");
}
This is not a programming question. Firstly, if you're on not an a dynamically-assigned IP address (that is likely spam-blocked by many mail servers), you don't need an SMTP server. You just take "toaddress#domain" and resolve the "domain" part to a mail exchange handler (DNS MX record lookup) make a direct SMTP connection to that server and put your mail there. You don't program this yourself because mail-handling applications or middleware should know how to do this all by itself.
If you're not on a clean static IP address, you probably can't do that because many SMTP servers will reject connections from such addresses (a common source of spam!).
In that case, your first solution is to relay through the SMTP server provided by your internet provider. (It may be secured, so you have to set up your authentication credentials.)
If that doesn't work (e.g. it is too insecure or otherwise spam-friendly and so widely black-listed) then you look elsewhere for SMTP sending solutions.
Nobody can answer this for you because the best SMTP server depends on how you are hooked up to the Internet.

Resources