Javamail - Send mail over SSL
must send a mail use a SMTP with SSL.
This is an example of my code :
publicvoid sendMail(String destinatario,String mittente,String oggetto,String messaggio,String fileName,String fileNameInMail)throws Exception
{
if (protocol.equals("smtps")){
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
}
props=System.getProperties();
props.setProperty("mail."+protocol+".host", mailServer);
props.setProperty("mail.transport.protocol", protocol);
if (protocol.equals("smtps")){
props.setProperty("mail.smtps.auth","true");
props.setProperty("mail.smtps.starttls.enable","true");
props.setProperty("mail.smtps.socketFactory.fallback","false");
props.setProperty("mail.smtps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtps.socketFactory.port", UtilitaGenerale.getStringa(port));
}
Authenticator auth=null;
if(!mailUser.trim().equals(""))
auth=new MyAuthenticator(mailUser,mailPassword);
boolean debug =false;
//Session session = Session.getInstance(props,auth);
Session session=Session.getInstance(props,auth);
session.setDebug(true);
try{
Message msg =new MimeMessage(session);
Address mit=new InternetAddress(mittente);
msg.setFrom(mit);
InternetAddress[] address ={new InternetAddress(destinatario)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(oggetto);
MimeBodyPart textPart =new MimeBodyPart();
textPart.setContent(messaggio,"text/plain");
MimeBodyPart attachFilePart =new MimeBodyPart();
FileDataSource fds =new FileDataSource(fileName);
attachFilePart.setDataHandler(new DataHandler(fds));
attachFilePart.setFileName(fileNameInMail);
Multipart mp =new MimeMultipart();
mp.addBodyPart(textPart);
mp.addBodyPart(attachFilePart);
msg.setContent(mp);
Transport transportTemp=null;
transportTemp= session.getTransport(protocol);
transportTemp.connect(mailServer,port,mailUser,mailPassword);
transportTemp.send(msg);
transportTemp.close();
}
catch(Exception e)
{
throw e;
}
finally
{
session=null;
}
}
but I obtain this error :
javax.mail.MessagingException: Exception reading response
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1427)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1225)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:340)
at javax.mail.Service.connect(Service.java:275)
at it.maggioli.informatica.conciliaweb.applicazione.service.mail.InviaLotto.inviaLotto(InviaLotto.java:158)
at it.maggioli.informatica.conciliaweb.applicazione.service.GestioneInvioLotto.inviaLotto(GestioneInvioLotto.java:236)
at it.maggioli.informatica.conciliaweb.applicazione.service.GestioneInvioLotto.inviaLottoNotifiche(GestioneInvioLotto.java:53)
at it.maggioli.informatica.conciliaweb.interfacciaclientserver.richiesteclient.EsecutoreSingolaRichiesta.eseguiRichiesta(EsecutoreSingolaRichiesta.java:1285)
at it.maggioli.informatica.conciliaweb.interfacciaclientserver.richiesteclient.EsecuzioneRichieste.eseguiRichiesteWindows(EsecuzioneRichieste.java:74)
at it.maggioli.informatica.conciliaweb.interfacciaclientserver.richiesteclient.EsecuzioneRichieste.eseguiRichieste(EsecuzioneRichieste.java:93)
at it.maggioli.informatica.conciliaweb.serlvets.AJAX.EsecuzioneRichiesta.processRequest(EsecuzioneRichiesta.java:153)
at it.maggioli.informatica.conciliaweb.serlvets.AJAX.EsecuzioneRichiesta.doPost(EsecuzioneRichiesta.java:50)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.planetj.servlet.filter.compression.CompressingFilter.doFilter(CompressingFilter.java:217)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Thread.java:619)
Caused by: 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
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1520)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:182)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:176)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:975)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:123)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:511)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:449)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:817)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1029)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:677)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1405)
... 28 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:285)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:191)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:954)
... 40 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:280)
... 46 more
I have use the option debug of javamail and i have Obtain this :
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "sendm.cert.legalmail.it", port 465, isSSL true
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
Can you help me ?
Sorry for my bad english.
[10561 byte] By [
Lepr8a] at [2007-11-27 5:45:54]

# 1
Your server is probably using a non-standard certificate, perhaps aself-signed certificate. The Java SSL support library (JSSE) isn't ableto verify the validity of such a certificate. See the SSLNOTES.txt fileincluded with JavaMail for tips on how to handle this.
# 2
I have been working on this exact problem, and am having no success.
I read the notes in SSLNotes.txt, and just for giggles, implemented the completely insecure example they provided (all certificates are trusted). And I get the following exception:
javax.mail.MessagingException: Could not connect to SMTP host: mail.xxxx.net, port: 465;
nested exception is:
java.net.SocketException: Unconnected sockets not implemented
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at sunspot.spotmanager.BugReporter.submitConfig(BugReporter.java:373)
at sunspot.spotmanager.BugReporter.access$000(BugReporter.java:35)
at sunspot.spotmanager.BugReporter$1.actionPerformed(BugReporter.java:166)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1882)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2202)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:231)
at java.awt.Component.processMouseEvent(Component.java:5554)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
at java.awt.Component.processEvent(Component.java:5319)
at java.awt.Container.processEvent(Container.java:2010)
at java.awt.Component.dispatchEventImpl(Component.java:4021)
at java.awt.Container.dispatchEventImpl(Container.java:2068)
at java.awt.Component.dispatchEvent(Component.java:3869)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4256)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3936)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3866)
at java.awt.Container.dispatchEventImpl(Container.java:2054)
at java.awt.Window.dispatchEventImpl(Window.java:1774)
at java.awt.Component.dispatchEvent(Component.java:3869)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:176)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Caused by: java.net.SocketException: Unconnected sockets not implemented
at javax.net.SocketFactory.createSocket(SocketFactory.java:97)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:222)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
... 31 more
Properties mailProps = new Properties();
mailProps.put("mail.smtps.host",this.smtp);
mailProps.put("mail.debug", "true");
mailProps.setProperty("mail.smtps.auth", "true");
mailProps.setProperty("mail.smtps.ehlo", "false");
mailProps.setProperty("mail.smtps.starttls.enable","true");
mailProps.setProperty( "mail.smtps.socketFactory.fallback", "false");
mailProps.setProperty( "mail.smtps.socketFactory.class", "sunspot.spotmanager.DummySSLSocketFactory");
mailProps.setProperty( "mail.smtps.socketFactory.port", "465");
Security.addProvider( new com.sun.net.ssl.internal.ssl.Provider());
java.security.Security.setProperty("ssl.SocketFactory.provider",
"DummySSLSocketFactory");
...
Transport tr = session.getTransport("smtps");
tr.connect(this.smtp, "myUser", "myPass");
tr.sendMessage(myMessage, myMessage.getAllRecipients());
tr.close();
is the basic code I am using, and ... well, failing. ANY help would be greatly appreciated!!
# 3
There was a bug in the example code. The fix is described here: http://forum.java.sun.com/thread.jspa?forumID=43&threadID=740854
# 4
Thanks for that tip, that took care of the Unopened Socket problem. But ...
This is so weird, as it was working fine until we turned off mail-relay on the server I was using ... NOW the error is:
Went online ... Fri Jun 01 21:26:18 EDT 2007
DEBUG: JavaMail version 1.4ea
DEBUG: java.io.FileNotFoundException: /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/javamail.providers (No such file or directory)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: not loading resource: /META-INF/javamail.default.providers
DEBUG: failed to load any providers, using defaults
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,Sun Microsystems, Inc.,1.4ea], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4ea], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc.,1.4ea], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc.,1.4ea], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc.,1.4ea], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc.,1.4ea]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc.,1.4ea], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc.,1.4ea], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4ea], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc.,1.4ea], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4ea], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc.,1.4ea]}
DEBUG: not loading resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException: /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/javamail.address.map (No such file or directory)
DEBUG: failed to load address map, using defaults
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4ea]
DEBUG SMTP: useEhlo false, useAuth true
DEBUG SMTP: trying to connect to host "mail.myserver.net", port 465, isSSL true
220 mail.myserver.net ESMTP
DEBUG SMTP: connected to host "mail.myserver.net", port: 465
HELO DavidsMacBookPro.local
250 mail.galaxy.net
DEBUG SMTP: use8bit false
MAIL FROM:<davidgs@xxxxxx.com>
250 ok
RCPT TO:<info@myserver.net>
250 ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP:info@myserver.net
DATA
354 go ahead
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type text/plain
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:885)
at javax.activation.DataHandler.writeTo(DataHandler.java:316)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1683)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:585)
at sunspot.spotmanager.BugReporter.submitConfig(BugReporter.java:375)
at sunspot.spotmanager.BugReporter.access$000(BugReporter.java:35)
at sunspot.spotmanager.BugReporter$1.actionP
huh? I swear, this was working until I had to authenticate. Now I get a MIME type exception ...
Ideas? I have RTFMed, to no avail ...
# 5
Something is broken in your setup. Are you using the mail.jar file unmodified?
Have you changed your CLASSPATH setting?
JavaMail is unable to find the needed configuration files in the mail.jar file.
That's usually because you've modified mail.jar (e.g., by extracting all the
class files and putting them elsewhere) or because the ClassLoader you're
using in your environment is broken.
# 6
Yup, you were right, I hadnt properly updated the jar file ... I had removed much of the contents of the META-INF directory for various reasons. I put it all back, except the signatures, so I could self-sign the jars (because otherwise the various jars are signed by different certificates, and won't run under java WebStart). So that fixed that ... but caused something else ...
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
at javax.mail.Session.loadProvidersFromStream(Session.java:928)
at javax.mail.Session.access$000(Session.java:174)
at javax.mail.Session$1.load(Session.java:870)
at javax.mail.Session.loadResource(Session.java:1084)
at javax.mail.Session.loadProviders(Session.java:889)
at javax.mail.Session.<init>(Session.java:210)
at javax.mail.Session.getDefaultInstance(Session.java:299)
at javax.mail.Session.getDefaultInstance(Session.java:339)
Which seems odd to me. I didn't delete anything down inside the javax.mail, etc. hierarchy, but now I get this exception.
I feel silly, since every fix finds another problem, but I'm stumped ...
# 7
Well, obviously you should compare the contents of your mail.jar filewith the original mail.jar file. Looks like you lost the "com" directory.