Java send mail, Takes time in Activation - java

I need to send a mail using SMTP of Gmail, and javax.mail api.
The same code I'm using, runs successfully in Android, If I take it to a Java Application or tries to use it in a Java Web Application it starts making troubles.
I spent time trying to understand what is the difference but no way!
My code is as following:
public class GMailSender extends Authenticator
{
private final String mailhost;
private final String password;
private final Session session;
private final String user;
public GMailSender(String username, String password)
{
this.mailhost = "smtp.gmail.com";
this.user = username;
this.password = password;
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.host", mailhost);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.debug", "true");
properties.setProperty("mail.smtp.quitwait", "false");
System.out.println("Creating session ...");
session = Session.getInstance(properties, this);
System.out.println("Session createed ...");
}
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
System.out.println("Authintecation ...");
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String dataHandler, String senderAddress, String recepeintAddress)
throws Exception
{
MimeMessage mimemessage;
mimemessage = new MimeMessage(session);
DataHandler datahandler = new DataHandler(new ByteArrayDataSource(dataHandler.getBytes(), "text/plain"));
mimemessage.setSender(new InternetAddress(senderAddress));
mimemessage.setSubject(subject);
mimemessage.setDataHandler(datahandler);
mimemessage.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recepeintAddress));
System.out.println("Sending ...");
Transport transport = session.getTransport("smtp");
transport.send(mimemessage);
System.out.println("Sent!");
}
static {
Security.addProvider(new JSSEProvider());
}
public static void main(String[] args){
System.out.println("Starting email ...");
GMailSender sender = new GMailSender("myEmail#gmail.com", "my password");
try {
sender.sendMail("Test", "alot of data", "myEmail#gmail.com", "someonesemail#gmail.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public final class JSSEProvider extends Provider {
private static final long serialVersionUID = 1L;
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController
.doPrivileged(new java.security.PrivilegedAction<Void>() {
#Override
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
});
}
}
When I run my code I got the following:
> Starting email ...
> Creating session ...
> Session createed ...
> Sending ...
> Authintecation ...
Then it takes around 10 min to return with the following:
> javax.mail.MessagingException: Could not connect to SMTP host:
> smtp.gmail.com, port: 465, response: -1
> at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1379)
> at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
> at javax.mail.Service.connect(Service.java:310)
> at javax.mail.Service.connect(Service.java:169)
> at javax.mail.Service.connect(Service.java:118)
> at javax.mail.Transport.send0(Transport.java:188)
> at javax.mail.Transport.send(Transport.java:118)
> at com.srycrm.mail.GMailSender.sendMail(GMailSender.java:66)
> at org.apache.jsp.send_jsp._jspService(send_jsp.java:85)
> at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
> at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
> at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
> at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
> at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
> at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
> at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Anyone can help me please!!
Thank you.

Ok you are using port 465, so enable ssl mail.smtp.ssl.enable to true :
properties.put("mail.smtp.ssl.enable", "true");
if it doesn;t work , then have properties.put("mail.smtp.starttls.enable", "true"); and change port to 587 and see if it helps.

Great!
Thanks for all the people that tried to help.
The Solution is a bit strange! I just downgraded my JRE and JDK to 1.6 and this solved the problem!
It might be something with the Java 1.7 enviroment.
Anyway, Thanks for all you are like always awesome :)

There's a bunch of errors in your code. Start here to fix the most common mistakes.
After that, see the JavaMail FAQ for connection debugging tips. Post the debug output here if you can't figure it out.

Related

How to connect to office365 using IMAPS protocol from Java application

There are few articles out there about this, but non of them worked for me. Basically I have following java code to connect to office 365:
Properties props = new Properties();
props.put("mail.imaps.auth.plain.disable", "true");
props.put("mail.imaps.ssl.enable", "true");
session = Session.getInstance(props, null);
store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
but it fails with LOGIN failed error;
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:725)
at javax.mail.Service.connect(Service.java:366)
Also I'm able to login into my account using IMAPS from Thunderbird.
Any pointers to resolve an issue would be appreciated!
This code works for me for outlook I have modified it for use with Office365. I did the research to find the IMAP host for office 365. I hope it helps you.
public static void main(String[] args) throws MessagingException {
MultiPartEmail email = new MultiPartEmail();
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
//extra codes required for reading OUTLOOK mails during IMAP-start
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
//extra codes required for reading OUTLOOK mails during IMAP-end
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", "some.one#some.org", "mypassword");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
inbox.addMessageCountListener(new MessageCountListener() {
#Override
public void messagesAdded(MessageCountEvent messageCountEvent) {
Message[] messages = messageCountEvent.getMessages();
System.out.println("A message was added, you now have: " + messages.length + " emails");
}
#Override
public void messagesRemoved(MessageCountEvent messageCountEvent) {
}
});
while (true) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
inbox.getMessageCount(); // Keeps connection alive
}
}
As it turned out, office 365 was rejecting connections because of unsupported characters inside the password. Particularly quote character. So, as simple as changing psw fixed my problem.
And following code snippet works just fine:
Properties props = new Properties();
props.put("mail.store.protocol", "imaps");
session = Session.getInstance(props, null);
store = session.getStore();
store.connect("outlook.office365.com", 993, "user#mydomain.com", "psw");
With 'javax.mail', version: '1.5.6'

Can someone help in writing Java program to download Sharepoint Lists?

I wrote below program to download SharePoint lists. But I am getting errors while using sharepointclient and listsoapstub. Does they have any dependency on other API's or jar files ? If so, what will be those ?
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class SimpleAuthenticator extends Authenticator
{
private final String username;
private final char[] password;
public SimpleAuthenticator(final String username, final String password)
{
super();
this.username = new String(username);
this.password = password.toCharArray();
}
#Override
public PasswordAuthentication getPasswordAuthentication()
{
return (new PasswordAuthentication (username, password));
}
}
SimpleAuthenticator authenticator = new SimpleAuthenticator(username,
password);
Authenticator.setDefault(authenticator);
public class SPClient
{
private static String username = "your sharepoint username";
private static String password = "your sharepoinnt password";
private static String BasesharepointUrl = "https://mysharepoint.com/Book Names";
private static ListsSoap listsoapstub;
private static VersionsSoap versionssoapstub;
private static CopySoap copysoapstub;
private static SharePointClient getInstance()
{
return(new SharePointClient());
}
public static void main(String[] args)
{
try
{
NtlmAuthenticator authenticator = new NtlmAuthenticator(username, password);
Authenticator.setDefault(authenticator);
//Authenticating and Opening the SOAP port of the Copy Web Service
listsoapstub = SharePointClient.getSPListSoapStub(username, password, BasesharepointUrl);
// Displays the lists items in the console
SharePointClient.displaySharePointList();
}
catch (Exception ex)
{
ex.printStackTrace();
System.err.println(ex);
}
}
}
I'm guessing that you got the code that you "wrote" from here:
http://blog.ashwani.co.in/blog/2013-07-28/connect-and-access-sharepoint-webservice-from-java/
(Your code looks strikingly similar to that code!)
I think the answer to your question is covered in these described in that blog posting:
Step 1. Download the wsdl files from the sharepoint.
Step 2. Generate Java Stubs for these wsdls
Step 3. Place the WSDLs in your resources
Once you have done that, you should be able to add imports for the relevant classes to the classes that you wrote.

Unable to connect to SSH in Java

I'm trying to use JSch in Java to connect to one of my EC2 instances, but keep getting an "UnknownHostKey" exception message. Here's is (part of) my code:
import com.jcraft.jsch.*;
import java.io.*;
public class JSchTest {
private String serverIp;
public void testSshConnection() {
try {
JSch jsch = new JSch();
jsch.addIdentity("C:\\Users\\Administrator\\.ssh\\id_rsa");
Session session = jsch.getSession("ec2-user", serverIp, 22);
session.connect(30000); // <-- this is where the exception is thrown
ChannelExec channel = (ChannelExec)session.openChannel("shell");
// more code here...
channel.disconnect();
session.disconnect();
} catch (JSchException|IOException ex) {
ex.printStackTrace();
}
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
}
I've already added my public key to the authorized_keys file on the EC2 instance that I'm connecting to, and I know it works because I can connect to it using PuTTY. However as soon as I hit the line with the session.connect() in it, I get an exception like this:
com.jcraft.jsch.JSchException: UnknownHostKey: 10.114.2.115. RSA key fingerprint is 63:04:cf:60:4a:1d:47:35:12:0e:56:4f:5b:0a:c9:d4
What am I missing? How can I get this to connect?
Try this:
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
As per this link.

JavaMail SocketException: Connection reset

I'm trying to send emails through JavaMail API but I end up receiving the SocketException: Connection reset.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("userName#gmail.com","gmailPassword");
}
};
Session session = Session.getDefaultInstance(props,auth);
try {
Message message = new MimeMessage(session);
Address sender = new InternetAddress("any#...");
message.setFrom(sender);
String recipients = "email1#...,email2#...,email2#...";
String[] toList = recipients.split(",");
System.out.println(toList.length);
Address[] addressTo = new InternetAddress[toList.length];
for(int i = 0; i < toList.length; i++){
addressTo[i] = new InternetAddress(toList[i]);
}
for( int i=0; i < addressTo.length; i++) { // changed from a while loop
message.addRecipient(Message.RecipientType.TO, addressTo[i]);
}
message.setSubject("Testing Subject 5");
message.setText("Dear Message ," +
"\n\n HELLO, please! \n https://192.168.192.120:8181/centralWeb");
System.out.println("SENDING MAIL......... " + new Date().toString());
message.setHeader("Content-type", "text/html; charset=UTF-8");
Transport.send(message);
System.out.println("Done " + new Date().toString());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
NetBeans Output:
1
SENDING MAIL......... Sun Apr 28 01:30:18 IST 2013
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at sendmailssl.SendMailSSL.main(SendMailSSL.java:65)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at sendmailssl.SendMailSSL.main(SendMailSSL.java:60)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:312)
at sun.security.ssl.InputRecord.read(InputRecord.java:350)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:503)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
... 7 more
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I've tried disabling IPv6 and turning off my firewall too, but the problem persists. I am using Windows 7 x64, if that matters.
Thanks to anyone who can help me fix this issue.
Try these debugging tips from the JavaMail FAQ:
How do I debug my application that uses JavaMail APIs?
How do I debug problems connecting to my mail server?
Also, you might want to correct these common mistakes, although I don't think they're related to your problem.

Fatal Exception re WAS AdminClient

I'm attempting to monitor a Websphere 7 ennvironment using MBeans, but running into numerous problems. First, I receive the following exception when using the code posted below:
com.ibm.websphere.management.exception.ConnectorException: Could not
create RMI Connector to connect to host localhost at port 2809
Here is the code generating the exception:
import java.util.Properties;
import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
public class JustAdminClient {
private AdminClient adminClient;
private void initialize() throws Exception {
try {
// Initialize the AdminClient.
Properties adminProps = new Properties();
adminProps.setProperty("type", AdminClient.CONNECTOR_TYPE_RMI);
adminProps.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "false");
adminProps.setProperty(AdminClient.CONNECTOR_HOST, "localhost");
adminProps.setProperty(AdminClient.CONNECTOR_PORT, "2809");
adminClient = AdminClientFactory.createAdminClient(adminProps);
} catch (Exception ex) {
ex.printStackTrace(System.out);
throw ex;
}
} // end method
/**
* #param args
*/
public static void main(String[] args) {
JustAdminClient adClient = new JustAdminClient();
try {
adClient.initialize();
} catch (Exception e) {
e.printStackTrace();
}
} // end main
} // end class
Second, I'm running WAS standalone with security disabled. Do I need to configure any self-signed certs?
My security.xml shows:
<security:Security xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
xmlns:orb.securityprotocol="http://www.ibm.com/websphere/appserver/schemas/5.0/orb.securityprotocol.xmi"
xmlns:security="http://www.ibm.com/websphere/appserver/schemas/5.0/security.xmi" xmi:id="Security_1"
useLocalSecurityServer="true" useDomainQualifiedUserNames="false"
issuePermissionWarning="true" activeProtocol="BOTH"
enforceJava2Security="false" enforceFineGrainedJCASecurity="false"
appEnabled="true" dynamicallyUpdateSSLConfig="true"
allowBasicAuth="true" activeAuthMechanism="LTPA_1"
activeUserRegistry="LocalOSUserRegistry" enabled="false" cacheTimeout="600"
defaultSSLSettings="SSLConfig_RXCW510MONNode01_1" adminPreferredAuthMech="RSAToken_1">
per the link: http://www-01.ibm.com/support/docview.wss?uid=swg21295051
Note, I can contact port 2809 two ways, via WSadamin and a Java prog containing the following:
private void connect(String host,String port) throws Exception
{
String jndiPath="/WsnAdminNameService#JMXConnector";
JMXServiceURL url = new JMXServiceURL("service:jmx:iiop://"+host+"/jndi/corbaname:iiop:"+host+":"+port+jndiPath);
System.out.println("URL = " + url);
//JMXServiceURL url = new JMXServiceURL("service:jmx:iiop://192.168.0.175:9100/jndi/JMXConnector");
Hashtable h = new Hashtable();
//Specify the user ID and password for the server if security is enabled on server.
//Establish the JMX connection.
System.out.println("Before JMXConnector");
JMXConnector jmxc = JMXConnectorFactory.connect(url, h);
//Get the MBean server connection instance.
System.out.println("Before getMBeanServerConnection");
mbsc = jmxc.getMBeanServerConnection();
System.out.println("Connected to Application Server");
} // end method
Any ideas? I'm lost and apologize for the long thread, but better to see the info upfront.
Resolved my problem using the follwoing example code snippet and notations. Note, pay particular attention to thrown exception and messages re: mssing classes; i.e. focusing on the message "could not create" message may mislead you
requires the following jar files:
%WAS_HOME%\runtimes\com.ibm.jaxws.thinclient_7.0.0.jar
%WAS_HOME%\plugins\com.ibm.ws.runtime.jar
%WAS_HOME%\plugins\deploytool\itp\com.ibm.websphere.v7_7.0.0.v20080817\wasJars\com.ibm.ws.admin.core.jar
%WAS_HOME%\runtimes\com.ibm.ws.admin.client_7.0.0.jar requires
CONNECTOR_TYPE_SOAP. CONNECTOR_TYPE_RMI fails to connect; maybe a jar issue based on the stack trace messages
public class JMXAdminClientSimple {
`private AdminClient adminClient;
private ObjectName nodeagent = null;
public void initialize() throws Exception {
try {
// Initialize the AdminClient.
Properties props = new Properties();
props.setProperty(AdminClient.CONNECTOR_HOST, "localhost");
props.setProperty(AdminClient.CONNECTOR_PORT, "8880");
props.setProperty(AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
props.setProperty(AdminClient.CONNECTOR_SECURITY_ENABLED, "false");
props.setProperty(AdminClient.USERNAME, "");
props.setProperty(AdminClient.PASSWORD, "");
adminClient = AdminClientFactory.createAdminClient(props);
} catch (Exception ex) {
ex.printStackTrace(System.out);
throw ex;
}
}`
To use the AdminClient API with security disabled on a Sun/Oracle JRE, you need the following JARs in the classpath:
runtimes/com.ibm.ws.admin.client_7.0.0.jar
runtimes/com.ibm.ws.ejb.thinclient_7.0.0.jar
runtimes/com.ibm.ws.orb_7.0.0.jar
With these JARs, RMI should also work.

Categories

Resources