public class ConnectGmail {
public static void main(String args[]) throws Exception {
PasswordAuthentication authentication;
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
Session session = Session.getDefaultInstance(props);
Store store = session.getStore("imap");
try {
store.connect(host , user , "password");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Got this ERROR .. I almost tried with all the protocol
javax.mail.MessagingException: Connection refused: connect;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:571)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at ConnectGmail.main(ConnectGmail.java:26)
any help ??
You need to enable the mail authentification before you can use it:
Set property mail.smtp.auth to true to enalbe authentification.
If true, attempt to authenticate the user using the AUTH command. Defaults to false.
#see Javadoc of Package com.sun.mail.smtp
Does your ISP allow you to connect to that port?
Do you have to go through a proxy?
Try opening a direct connection to the mail server with the right port using a simple telnet <host> <port> command. If you can't then it's not your connection that fails, it's your ISP that disallows it. If you can, check if you use specific proxy options and add them in your program.
Related
Everything works, including authentication, but when I get to the step of creating a folder the program crashes.
I've tried switching to SMTP, didn't work, not even sure what SMTP is,
I've Tried a different Gmail account,
I've tried removing the line properties.put("mail.pop3.starttls.enable", "true"), and
I've tried removing the 3's from pop3 and pop3s.
private static void createProperties() {
// Create properties field.
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.store.protocol", "pop3s");
properties.put("mail.pop3.port", "995");
//properties.put("mail.pop3.starttls.enable", "true");
emailSession = Session.getDefaultInstance(properties, null);
}
private static void createStore() throws MessagingException {
// Create the POP3 store object and connect with the POP server.
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
}
private static void createFolder() throws MessagingException {
// Create the folder object and open it.
Folder emailFolder = store.getFolder("INBOX"); // Error here
emailFolder.open(Folder.READ_ONLY);
}
I expected to get some nicely formatted email messages.
I got the following errors:
DEBUG POP3: server doesn't support TOP, disabling it
Exception in thread "main" java.lang.NullPointerException
at GetMail.createFolder(GetMail.java:60)
at GetMail.main(GetMail.java:33)```
The POP3 protocol only supports one folder - Inbox. Use IMAP instead.
I have created automated email report using java mail api which needs to be triggered everyday after a batch file run.Although it works fine most of the times,at times it gives exception javax.mail.MessagingException: Could not connect to SMTP host: my host name, port: 25; nested exception is: java.net.ConnectException: Connection refused.This is not due to authentication issue as i use the same credentials whenever i sent the email.
I am not sure why java mail api fails intermittently.Can i get some suggestion to debug the issue?
I am using the below code snippet -
String to = "xyz#gmail.com";//change accordingly
String from = "abc#mydomain.com";//change accordingly
final String username = "abc";//change accordingly
final String password = "*****";//change accordingly
String host = "My SMTP server";
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", "25");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Testing Subject");
message.setText("message to stakeholders");
Transport.send(message);
}
It's a good idea to check logs on the mail server to see possible cause of the refusal - especially since you know WHEN failed attempts were made at.
If JavaMail can't connect "sometimes" with "connection refused", the possibilities are:
The server is actually down.
The server is up, but too busy to accept new connections.
The server is up, but is rejecting connections for some policy reason, e.g., you've connected too frequently.
Some firewall or anti-virus program has rejected the connection.
Check the server configuration and log files. If there's nothing on the server indicating that it's rejecting connections, check the client.
This question already has answers here:
Skipping Kerberos authentication prompts with JSch [duplicate]
(2 answers)
Closed 7 years ago.
I am trying to use JsCH for connecting to a remote server and then manipulate PostgreSQL.
Everything going fine if I use PUTTY and also with JSCH.
My only problem is the JsCH only accepts username and password from the Eclipse console even if I set these properties.
public void connect() {
//
int assigned_port;
final int local_port=5432;
// Remote host and port
final int remote_port=5432;
final String remote_host="myserver011";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
Session session = jsch.getSession("companyusername", remote_host, 22);
session.setPassword("password");
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
System.out.println("SSH Connection succes!");
} catch (JSchException e) {
e.printStackTrace();
LOGGER.log(Level.SEVERE, e.getMessage()); return;
}
if (assigned_port == 0) {
LOGGER.log(Level.SEVERE, "Port forwarding failed !");
return;
}
}
But the console still needs the username and password.
Kerberos username [myusername]: companyusername <---- here I set again the username
Kerberos password for companyusername : password <---- and the password
SSH Connection succes!
Opened database successfully
And then everything works. But I don't want to set these again, and I cant find anywhere the source of this "bug"?! I don't know, maybe it's a server config parameter to force the user to manually give the input?
Any advice or hint would be great.
//this works pretty well for me.
Session session;
ssh = new JSch();
session = ssh.getSession(username,hostname,port);
session.setConfig(config);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking","no");
session.connect();
One of my customers is using Gmail for business (part of Google Apps) and I had to reconfigure the website I've developed so it would match the new credentials. After a bit of struggle due to TLS errors, I've managed to make the code work on localhost and on my test server (both Apache Tomcat 5.5). Everything was going smooth until I had to move it on his server (another Tomcat 5.5 as the hosting company told me). On the client's server I get the following error:
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.io.IOException: Couldn't connect using "javax.net.ssl.SSLSocketFactory" socket factory to host, port: smtp.gmail.com, 465; Exception: java.lang.reflect.InvocationTargetException
The strange thing is that on localhost and the test server the port 465 works fine, and the guys from hosting said that port is opened on their server.
The code that connects to the mailserver is:
private void initConfigParams() throws CMSGeneralException {
try {
props = System.getProperties();
String smtpHost = Messages.getDBConfString("mail.smtp.host");
String mailPort = Messages.getDBConfString("mail.smtp.port");
String socketFallback = Messages.getDBConfString("mail.smtp.socketFactory.fallback");
String enableTls = Messages.getDBConfString("mail.smtp.starttls.enable");
String authSmtp = Messages.getDBConfString("mail.smtp.auth");
String tlsRequired = Messages.getDBConfString("mail.smtp.stattls.required");
String sktFactory = Messages.getDBConfString("mail.smtp.socketFactory.class");
props.put("mail.smtp.starttls.enable", enableTls);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", authSmtp);
props.put("mail.smtp.starttls.required", tlsRequired);
props.setProperty("mail.smtp.socketFactory.class", sktFactory);
props.setProperty("mail.smtp.socketFactory.fallback", socketFallback);
props.setProperty("mail.smtp.port", mailPort);
props.setProperty("mail.smtp.socketFactory.port", mailPort);
props.put("mail.transport.protocol", Messages.getDBConfString("mail.transport.protocol"));
Authenticator auth = null;
userName = Messages.getDBConfString("mail.username");
userPassword = Messages.getDBConfString("mail.userpassword");
if (!CMSUtils.isEmptyString(userName) && !CMSUtils.isEmptyString(userPassword)){
/* props.put("mail.smtp.auth", "true"); */
auth = new SMTPAuthenticator(userName, userPassword);
}
session = Session.getDefaultInstance(props, auth);
session.setDebug(false);
address = new InternetAddress[1];
address[0] = new InternetAddress(recipients);
mbText = new MimeBodyPart();
mbText.setContent(text, "text/html");
mp = new MimeMultipart();
mp.addBodyPart(mbText);
} catch (MessagingException e) {
e.printStackTrace();
throw new CMSGeneralException();
}
}
With the following .properties file
mail.smtp.starttls.enable=true
mail.smtp.host=smtp.gmail.com
mail.smtp.auth=true
mail.smtp.starttls.required=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=false
mail.smtp.port=465
mail.transport.protocol=smtps
mail.username=website#example.com
mail.userpassword=password
mail.from=website#example.com
mail.to=mail#example.com
I tried the other ports for GMail, 587, but it doesn't work on any of the servers. Not even port 25 won't do the trick.
So, what am I doing wrong, and what should I do to make the mailing work?
Get rid of all the socket factory properties; if you're using a reasonably recent version of JavaMail you don't need them. See the JavaMail FAQ for how to configure JavaMail to access Gmail. You'll also find debugging tips there if it still doesn't work.
Also, change Session.getDefaultInstance to Session.getInstance.
And finally, if you're setting "mail.transport.protocol" to "smtps", you need to set the other properties as "mail.smtps." properties, not "mail.smtp." properties.
It seems to you have problems with java.lang.reflect.InvocationTargetException. So, I mean it's not a network problem. May be you've specified some parameters wrong and JavaMail API routes couldn't invoke a method. May be you should also specify property mail.smtp.ssl.socketFactory.
Some documentation here http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html .
I have been working at home on Gmail-Imap-Api on the weekend. It was working Properly But when i returned to office and am trying here it throws exception.
Properties props = System.getProperties();
props.put("mail.store.protocol", "imaps");
props.put("mail.smtp.auth", "true");
try {
boolean debug = false;
Authenticator auth = new SMTPAuthenticator(
"***", "***");
Session session = Session.getInstance(props, auth);
session.setDebug(debug);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "***#gmail.com",
"****");
......
......
This was working fine at home netwrok.
Now i thought i would add proxy and added these lines of code.
System.setProperty("http.proxyHost", "****.com");
System.setProperty("http.proxyPort", "8080");
Still it doesnt work and the exception is.
com.google.code.javax.mail.MessagingException: imap.gmail.com;
nested exception is:
java.net.UnknownHostException: imap.gmail.com
at com.google.code.com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:665)
at com.google.code.javax.mail.Service.connect(Service.java:295)
at com.google.code.javax.mail.Service.connect(Service.java:176)
at openReports.OpenReportsProject.main(OpenReportsProject.java:43)
Caused by: java.net.UnknownHostException: imap.gmail.com
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:367)
at java.net.Socket.connect(Socket.java:524)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:545)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
at com.google.code.com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.google.code.com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.google.code.com.sun.mail.iap.Protocol.<init>(Protocol.java:113)
at com.google.code.com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:110)
at com.google.code.com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:632)
... 3 more
The proxy settings that you have entered will work only for HTTP connections. IMAP is a different protocol operating on a different port (993 in this case). If you are behind firewall, your firewall needs to allow connection to the external host:port AND the protocol. You need to request to your Network Administrator for this. Once the settings are in place you will be able to communicate to Gmail Imap server on default/specified port with specified protocol.