I'm having an issue with JavaMail programming in Netbeans. When I run the code below in the IDE, the email sends as intended. But when I perform a clean and build and attempt to perform the same action from the JAR Executable file, I receive the following information from the debugger:
DEBUG: JavaMail version 1.5.2
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[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 587, isSSL false
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.SocketException: Permission denied: connect
I have tried building with both JDK1.8 and JDK1.7 with no success. Many sites(for example, ) have suggested fixing the IPv6 issue with some variation of the following in the netbeans config folder: -Djava.net.preferIPv4Stack=true. I have placed this in the VM options as well, and as you can see below, I have also tried to implement it in my code. Other attempted fixes still in place are setting the socketFactor.class property to javax.net.ssl.SSLSocketFactory, setting the MailSSLSocketFactory TrustAllHosts to true, and using the sendMessage() method in an instance of the Transport class to send the email. All failed.
I have attempted to telnet gmail through port 587 and the cmd line, and the connection has been established successfully.
I'm a big fan of debugging things myself, but it's been over a week and while many people seem to share the SocketException issue, none of the solutions have been effective.
I am open to solutions to this problem or, frankly, any alternative ways to send emails with Java. Reading emails is not important for this code. Most helpful are code snippets rather than just descriptions so I can drop them into my code for running. Thanks in advance!
Relevant code segment (running in Windows 7):
static void sendEmail(String toAddress, String subject, String body) throws NoSuchProviderException, MessagingException, GeneralSecurityException {
try {
System.setProperty("java.net.preferIPv4Stack", "true");
String host = "smtp.gmail.com";
String username = "sampleuser#gmail.com";
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", host);
props.put("mail.smtp.port", "587");
props.put("mail.debug", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.password", password);
props.put("mail.smtp.user", "sampleuser");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
Session session = Session.getInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setText(body);
Transport t = session.getTransport("smtp");
try {
t.connect(host, username, password);
t.sendMessage(message, message.getAllRecipients());
}catch(Exception e){
System.out.println(e);
} finally {
t.close();
}
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Possibly the property needs to be set when the JVM starts? Try running with "java -Djava.net.preferIPv4Stack=true -jar ...."
Possibly you have some anti-virus or firewall that preventing "java" from connecting, but allowing "telnet" to connect? Try turning off any anti-virus or firewall temporarily to test.
Gmail now comes with Sign-in & Secure feature turned off by default. Turn it on for your account and should work fine.
https://myaccount.google.com/security
Related
I have a strange problem with a custom portlet on Liferay 7 to solve:
MailService.sendMail is working from MY COMPUTER with google smtp and a personal account: this means that the code is working...
On my HOST SERVER sending emails with the final-smtp works correctly: I tried both root and liferay user with telnet final-smtp port.
On the Liferay server on HOST SERVER, send e-mails works correctly: if I forget the password, Liferay send me the e-mail.
But ... if I try to send email with my portlet from Liferay on HOST SERVER it doesn't work without any error. I'm using Liferay MailService.sendMail. I post the code but it works (on MY COMPUTER).
I get the service in this way:
#Reference(unbind = "-")
protected void setMailService(MailService mailService) {
_mailService = mailService;
}
And the calling code is in the following:
InternetAddress fromAddress = null;
String newsletterPrefix = null;
InternetAddress toAddress = null;
try {
String smtpUser = PropsUtil.get(
"newsletter.send.mail.smtp.user");
String smtpToUser = PropsUtil.get(
"newsletter.send.mail.smtp.to.user");
if (Validator.isNotNull(smtpUser)) {
fromAddress = new InternetAddress(smtpUser);
}
if (Validator.isNotNull(smtpToUser)) {
toAddress = new InternetAddress(smtpToUser);
}
}
catch (Exception e) {
_log.error(e, e);
result = false;
}
MailMessage mailMessage = new MailMessage(
fromAddress, toAddress, subject, body, true);
mailMessage.setBCC(addressList);
_mailService.sendEmail(mailMessage);
There could be several reasons behind this, some not even code related.
I see you are using this code for a newsletter, which suggests you are using a smtp service that is meant for this.
It could be that your server is in fact sending the email, with success, but the smtp server is simply blocking, rejecting or marking to resend later. Moreover, that server might be configured to not send an error message, or sending an error message in the form of a successful delivery, but the data contains the error.
I would start checking you mail server configuration, and the accounts permissions, then its logs.
Also, you might consider using plugins for mass mail delivery, like this one: https://www.e-systems.tech/blog/-/blogs/connecting-liferay-to-mailgun
Few things you can do to debug this problem:
Make sure you are deploying the intended code on HOST machine. (Silly suggestion, but many times this is the problem.)
Try to set following package's Log level to ALL/DEBUG to see if it shows any problem in logs.com.liferay.mail.service
I'm trying to configure mail with an Exchange server.
This is my configuration
grails {
mail {
host = "mail.xxx.xx.xx"
port = 443
username = "username"
password = "password"
props = [ "mail.smtp.auth":"true",
"mail.smtp.port":"443",
"mail.smtp.ssl.enable" :"true"
]
}
}
I'm getting the following error
Message: org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketException: Connection reset. Failed messages: javax.mail.MessagingException: Exception reading response;
I know it's an issue with the props that I have to change, since this configuration works on my mail app.
I know that the port is correct, it uses SSL.
I also tried using these props
props = ["mail.smtp.timeout" : "100000",
"mail.smtp.starttls.enable" : "true",
"mail.smtp.EnableSSL.enable" : "true",
"mail.transport.protocol" : "smtps",
"mail.smtp.socketFactory.port" : "443",
"mail.smtp.auth" : "true",
"mail.smtp.socketFactory.class" : "javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback": "false",
"mail.debug" : "true"]
The debug result it this :
DEBUG: JavaMail version 1.5.1
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[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "xxx.xxx.xx.xx", port 443, isSSL true
It looks to me as a certificate problem. If you have access to a server not using SSL, I would test that first, otherwise you should:
Find the certificate issuer (If you don't know it, you could use openssl verify http://www.herongyang.com/Cryptography/OpenSSL-Certificate-Path-Validation-Tests.html)
Look a CA in your java keystore
Locate Either the default java keystore (How do I find out what keystore my JVM is using?) or the one you are using
List the keystore and look for a corresponding CA
If there is a CA then the problem is not likely to be this
If there is no corresponding CA, then obtain the CA certificate and import it to you keystore, restart the server, and should work again.
I had the very same issue a while back. If you are trying to access an exchange server within a network (organization), I believe the port number is the issue here. It could have been changed by the network admin.
Please contact the network administrator and explain to him that you are trying to access the Exchange Server and require the username, password and the relevant port number. Authentication could be optional if the app is run in-house, i.e.
props = ["mail.smtp.auth":"false"]
I hope this helps.
I tried to implement the post from Kirit Vaghelathat that I found under "Send e-mail using java" in my Netbeans project but it gives a failure all the time:
"DEBUG SMTP: trying to connect to host "smtp.mail.yahoo.com", port 465, isSSL false
DEBUG SMTP: exception reading response: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Oops something has gone pearshaped, tried to send an e-mail !"
I tried exactly the same in Eclipse, and there it works.
Only difference I can see is in Eclipse I run it as a stand alone class:
public class hellotest extends Object{
public static void main(String[] args) {
//code
While in Netbeans it is part of a bigger project and it will be called from another class:
public class SendEmail extends Object{
public void sendEmail(){
//code
Can anyone explain to me what I'm doing wrong in Netbeans?
Added on 22 Jan 2015 :
I did some smaller changes to where Netbeans has to find its libraries (as suggested in the Oracle javaMail API FAQ) but with no result. Debug messages are changed a bit as follows :
DEBUG: JavaMail version 1.5.2
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: setDebug: JavaMail version 1.5.2
6
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.mail.yahoo.com", port 465, isSSL false
Oops something has gone pearshaped, tried to send an e-mail !
In Eclipse it is still working, I compared the code word per word, it is identical.
Thanks, for replying in comments.
It is security problem.
Compare content of JRE/JDK security folders. In my system the paths are:
JRE
"c:\Program Files\Java\jdk1.7.0_67\jre\lib\security"
JDK
"c:\Program Files (x86)\Java\jre1.8.0_25\lib\security"
Versions are not really important.
And remember what is in your JRE is what is correct = working for you...
grails project. i use email plugin and getting an exception when try call method 'sendMail'
error:
Caused by: org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.NoSuchProviderException: Unable to locate provider for protocol: smtp. Failed messages: javax.mail.NoSuchProviderException: Unable to locate provider for protocol: smtp; message exceptions (1) are:
Failed message 1: javax.mail.NoSuchProviderException: Unable to locate provider for protocol: smtp
config.groovy
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "mymail#gmail.com"
password = "mypass"
props = ["mail.smtp.auth":"true",
//"mail.smtp.port":"465",
//"mail.debug":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
example of sending
sendMail {
to "fred#gmail.com"
subject "Hello Fred"
body 'How are you?'
}
what am I doing wrong?
solution
The error say Unable to locate provider for protocol: smtp. It seems you're missing some dependencies for the smtp protocol, which seems very odd, apparently you're missing javamail (?). Because the code seems good to me.
Have you tried to remove
"mail.smtp.port":"465",
"mail.debug":"true",
from your config? This is the only difference I see between your code and the official example.
Update: as GalmWing already stated, it seems to be a problem with your java.mail jar file. Please check this solution: Using Java to send emails on gmail account . It sounds to me like you have the same problem. Which java-version do you use?
add to config.groovy
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "email"
password = "pwd"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
use this code to send mails
def sendEmail(){
mailService.sendMail {
to "email","**email**"
from "email"
subject "Hi"
body 'Hi'
}
}
also dont forget to inject mailservice in your class
def mailService
this will inject the service to your class
and this configuration will be sufficient to send mails
I am trying to connect to gmail using SMACK API through XMPP server. but getting the
error : SASL authentication failed using mechanism PLAIN
you can check a glimpse of code. I got it from net only
ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
connection = new XMPPConnection(connConfig);
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
I checked in the smack debug window. it says in XML :
< invalid-authzid />
I am already having account on gmail and my gtalk is also running.
You need to set the authentication before you connect viz
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
must appear before connection.connect().
See my blog.
ConnectionConfiguration cc = new ConnectionConfiguration(
"vietnam.agilemobile.com", 5222, vietnam.agilemobile.com");
XMPPConnection connection = new XMPPConnection(cc);
try {
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.connect();
Log.e("LOGIN", "" + 111);
// You have to put this code before you login
Log.e("LOGIN", "" + 222);
// You have to specify your gmail addres WITH #gmail.com at the end
connection.login("nemodo", "123456", "resource");
Log.e("LOGIN", "" + 333);
// See if you are authenticated
System.out.println(connection.isAuthenticated());
} catch (XMPPException e1) {
e1.printStackTrace();
}
I also get this mistake, but i can not work.
For anyone looking for possible solutions to this many years after this was originally asked and answered, I recently was able to get past this authentication error by explicitly setting the authzid value on the XMPPTCPConnectionConfiguration.
I was running into an issue where my connection configuration worked fine for some client XMPP servers, but not for others, even though they were all using SASL PLAIN authentication. After some troubleshooting, I learned that the ones that were failing were expecting an authzid value. After adjusting my code to set this, it works in both the environments that were working before, as well as the environments that were failing.
Here is how I am building my connection configuration:
XMPPTCPConnectionConfiguration.builder()
.setHost(XMPP_DOMAIN)
.setXmppDomain(XMPP_DOMAIN)
.setPort(XMPP_PORT)
.setCompressionEnabled(true) // optional, not all servers will support this
.setUsernameAndPassword(XMPP_USER, XMPP_PASSWORD)
.setResource(XMPP_RESOURCE)
.setAuthzid(JidCreate.entityBareFrom(String.format("%s#%s", XMPP_USER, XMPP_DOMAIN))) // <-- this was the change I needed
.build();
Specifically I needed to add this line:
.setAuthzid(JidCreate.entityBareFrom(String.format("%s#%s", XMPP_USER, XMPP_DOMAIN)))