how to read email using java? - java

I can send email, but I am unable to read the emails.
Here is my code to connect to the mail server:
String host = "na-*****.*****.****.ea.com";
String username = "*****#*******.ea.com";
String password = "********";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
session.setDebug(true);
Store store = session.getStore("pop3");
store.connect(host, username, password);
Whenever I try to read email using the code,it throws the following error:
javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:210)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at DisplayMail.main(DisplayMail.java:18)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.readLine(Unknown Source)
at com.sun.mail.pop3.Protocol.readResponse(Protocol.java:683)
at com.sun.mail.pop3.Protocol.simpleCommand(Protocol.java:656)
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:109)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:261)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:206)
... 3 more
Can someone tell me what I'm doing incorrectly, or if more information is needed?

there are multiple email protocols (pop3, imap, exchange, etc) and depending on which protocol you want you will need to find a library (or roll your own) to speak the protocol of choice to access and download emails from a server.
I would suggest looking at the JavaMail API

Related

RabbitMQ Connection reset

I'm trying to connect a simple RabbitMQ using java code to my server (which is executing the RabbitMQ service).
Executing the following code (source here) gives me the java.net.SocketException: Connection Reset exception.
import java.io.*;
import java.security.*;
import com.rabbitmq.client.*;
public class test
{
public static void main(String[] args) throws Exception
{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("myIP"); //myIP is just dummy text, I have a real IP there
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("sesgo");
factory.setVirtualHost("vSESGO");
factory.useSslProtocol();
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare("rabbitmq-java-test", false, true, true, null);
channel.basicPublish("", "rabbitmq-java-test", null, "Hello, World".getBytes());
GetResponse chResponse = channel.basicGet("rabbitmq-java-test", false);
if(chResponse == null) {
System.out.println("No message retrieved");
} else {
byte[] body = chResponse.getBody();
System.out.println("Recieved: " + new String(body));
}
channel.close();
conn.close();
}
}
I've looked for an answer online and I've already tried:
Verifying the server has the port I'm connecting to opened.
Verifying the client does not block my connection with firewalls, etc.
Creating a new Virtual Host on RabbitMQ and giving permissions to it.
Verifying iptables is not blocking me at the server side.
Nothing seems to work, any ideas?
Full stacktrace here:
This trust manager trusts every certificate, effectively disabling peer verification. This is convenient for local development but prone to man-in-the-middle attacks. Please see http://www.rabbitmq.com/ssl.html#validating-cerficates to learn more about peer certificate validation.
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.security.ssl.InputRecord.readFully(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at java.io.DataOutputStream.flush(Unknown Source)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:147)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:153)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:294)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:63)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:921)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:880)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:838)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:990)
at test.main(test.java:25)
I had the same issue right here: RabbitMQ Connection reset Exception. Solution for Windows was to add backslash in rabbit config file for paths to certs and key.
I don't know if this applies to your situation, but I recently resolved a similar situation while testing RabbitMQ 3.8.3, and the cause was that the key I was referencing was password-protected, but I had failed to provide the password in the RabbitMQ config, like this:
ssl_options.password = password
Unfortunately there was absolutely nothing in the RabbitMQ logs about this, even with the log level set to debug. When testing via various clients, a connection was established, but RabbitMQ immediately sent a connection reset.
I had this exact same error and my issue was in the rabbitmq.conf file. I was trying to use a JKS file for the following ssl options. Generating my own self signed .pem files was able to help fix this. I followed this guide pretty closely https://www.codetd.com/en/article/12031242.
ssl_options.cacertfile = /etc/rabbitmq/ca_certificate.pem
ssl_options.certfile = /etc/rabbitmq/server_certificate.pem
ssl_options.keyfile = /etc/rabbitmq/server_key.pem

SSLHandshakeException: Remote host closed connection during handshake

I have the following method for retrieving messages from Gmail using imap
public static void main(String[] args)
{
Properties props = new Properties();
try
{
props.load(new FileInputStream(new File("smtp.properties")));
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("smtp.gmail.com", "******#gmail.com", "mypass");
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
int messageCount = inbox.getMessageCount();
Message[] messages = inbox.getMessages();
System.out.println("------------------------------");
for (int i = 0; i < 10; i++)
{
System.out.println("Mail Subject:- " + messages[i].getSubject());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
my smtp.properties contains
mail.smtp.host=smtp.gmail.com
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.auth=true
mail.smtp.port=465
I get the following when I run the program
javax.mail.MessagingException: Remote host closed connection during handshake;
nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:695)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at gmailsmpt.Main.main(Main.java:25)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:532)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:337)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:116)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:121)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:710)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:659)
... 3 more
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(Unknown Source)
... 14 more
How can I fix the issue?
First, clean up all these common mistakes. You don't need any socket factories.
Then try these connection debugging tips.
Possibly you have a firewall or anti-virus program that's preventing you from connecting.
The problem is that the default TLS version in JAVA jre1.8.0_141 1.0, however due to vulnerabilities in 1.0 a lot of email servers no longer accept connections. To instead use 1.2 directly in code this instruction worked for me when creating properties for sending mail:
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
For example:
Properties props = System.getProperties();
props.put("mail.smtp.host", mailHost);
props.put("mail.smtps.auth", mailAuth);
props.put("mail.transport.protocol", mailProtocol);
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
// Get a Session object
Session sess = Session.getInstance(props, null);
// construct the message
MimeMessage msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(mailUser));
Also note, you could just set that same property in the properties file you're loading (smtp.properties) at the start of your try block.
Are there more stacktraces? Older Java versions have problems with TLS handshakes with RSA keys with more than 1024 bit (may be also with keys having exactly bit byte).
This was fixed in Java 1.7 or Java 1.8.
try adding below to the properties:
properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");

Error sending email with gmail

I have the following code:
Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("ruth.sistem#gmail.com", "XXXXXX"));
email.setSSLOnConnect(true);
email.setFrom("ruth.sistem#gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("ruth.sistem#gmail.com");
email.send();
I can not connect to gmail, an error burst with connection appears, however all connection information are correct, do not know what is blocking the connection from my code for sending the email, I can not send a simple email and I do not slightest idea what it is.
org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.googlemail.com:465
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1410)
at org.apache.commons.mail.Email.send(Email.java:1437)
at com.observatorioLegislativo.util.EmailTeste.enviaEmailSimples(EmailTeste.java:27)
at com.observatorioLegislativo.util.EmailTeste.<init>(EmailTeste.java:13)
at com.observatorioLegislativo.bean.Teste.main(Teste.java:41)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.googlemail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1400)
... 4 more
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:317)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:207)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
... 11 more
appreciate the help
I believe that snippet is taken from the Apache Commons Email API User Guide.
GMail blocks Access for less secure apps by default for security reasons so this might be causing your problem (as it did mine).
Log in to your GMail account and go to this URL:
https://www.google.com/settings/security/lesssecureapps
Set to Enable.
Email email = new SimpleEmail();
try {
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(
new DefaultAuthenticator("hogwarts-mailer#gmail.com", "password"));
email.setSSLOnConnect(true); // disable in case of EmailException
email.setFrom("hogwarts-school#gmail.com", "Hogwarts School");
email.setSubject("Hogwarts Acceptance Letter");
email.setMsg("We are pleased to inform you that you have a place at "
+ "Hogwarts School of Witchcraft and Wizardry.");
email.addTo("harry-potter#hedwig.com");
email.send();
} catch(EmailException ee) {
ee.printStackTrace();
}
DISCLAIMER:
By doing so, you have disabled one of GMail's security features.
Proceed at your own risk (or use a dummy email).
Related reading: Sending E-Mail Using GMail SMTP via Apache Commons Emails
Not required to put it in try and catch only changing the settings in gmail to allow lesser secure apps will do.
Just go to:
1.My account>>Sign in & Security>>Scroll to the bottom of the page and u will see the section:"Allow less secure apps: OFF"
2.Just turn it on and it will be done.
Img:Secure access image
This happened to me as well when I tried to send email from ktor server app using SimpleEmail. The difference in my case was that I had my email at custom g-suit domain with 2-step verification turned on and I couldn't use "less secure apps" settings:
This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access
I generated app spefific password and used it instead of my main gmail password and it worked.
val email = SimpleEmail()
email.hostName = "smtp.gmail.com"
email.setSmtpPort(587)
email.setAuthenticator(DefaultAuthenticator("info#customdomain.app", "APPLICATION_SPECIFIC_PASSWORD"))
email.isSSLOnConnect = true
email.setFrom("info#customdomain.app")
email.subject = "TestMail"
email.setMsg("This is a test mail... :-)")
email.addTo("foo#bar.com")
email.send()
Create app password info
Since Google has disabled 3rd party app access
you may need to create an App password and use that in your application it may work.
you can create an app password from here.
val email = SimpleEmail()
email.hostName = "smtp.googlemail.com"
email.setSmtpPort(587)
email.setAuthenticator(DefaultAuthenticator("YOUR_EMAIL", "APP_PASSWORD"))
email.isSSLOnConnect = true
email.setFrom("YOUR_EMAIL")
email.subject = "Test Email"
email.setMsg("Mail testing")
email.addTo("recipient email.")
val mime = email.send()
Try smtp.gmail.com, and Port 587. These are the settings I use. (With STARTTLS, but 'normal' password for authentication....I believe your SSLOnConnect is fine the way it is)
The JavaMail FAQ has tips for debugging connection problems.
Most likely there's a firewall or antivirus program preventing you from connecting.

MailConnectException while sending mail using java mail api

Trying to send an email using java mail api. And I keep getting MailConnectException. I have tried multiple ways to solve it without success.
Exception is thrown by this statement
transport.connect("smtp.gmail.com", "someone#gmail.com", "myPassword");
Can anyone tell me what I'm doing wrong?
public static void main(String[] args) {
String host = "smtp.gmail.com";
String from = "someone#gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "myPassword");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
try{
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, "someone#hotmail.com");
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", "someone#gmail.com", "myPassword");//CAUSES EXCEPTION
transport.sendMessage(message, message.getAllRecipients());
}catch(MessagingException e){
e.printStackTrace();
}
}
Stack trace:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1984)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:656)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at com.karmacrafts.util.CustomEmail.main(CustomEmail.java:127)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:301)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
... 4 more
This looks like network problem. Even though it could occur due to variety of reasons, like :-
"Couldn't connect to host, port" could be caused by wrong host name, wrong port, a blocking firewall (on the server, on gateways, even on your own machine), network failure, server downtime, etc.
Can you connect to the mail server using telnet ?
Also see this FAQ for some mistakes you committed http://www.oracle.com/technetwork/java/javamail/faq/index.html#commonmistakes
Read this answer on how to send emails using gmail https://stackoverflow.com/a/47452/3107043
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
props.put("mail.smtp.port", "587"); transport.send(message);
After 8 hours of pain, I've solved this by turning off:
1) my windows firewall
2) my antivirus software
hope this helps
I met the same problem, and the reason is that I opened a vpn. Hope this will be helpful.
For me, de-activating firewall and anti-virus did not work.
I tried the alternate ports given in the mailtrap's SMTP settings
25 or 465 or 587 or 2525
changing spring.mail.port to 2525 in the applications.properties file worked for me
Open /etc/postfix/main.cf
Search /inet_interfaces line and comment localhost, un-comment all:
Restart the SMTP server using terminal command "postfix restart"

Create a jTDS connection string

my sql server instance name is MYPC\SQLEXPRESS and I'm trying to create a jTDS connection string to connect to the database 'Blog'. Can anyone please help me accomplish that?
I'm trying to do like this:
DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/Blog", "user", "password");
and I get this:
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:395)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at SqlConnection.Connect(SqlConnection.java:19)
at main.main(main.java:11)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:305)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:255)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:323)
... 6 more
As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC, you may end up with something like this:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
Or, if you prefer to use getConnection(url, "sa", "s3cr3t"):
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
EDIT: Regarding your Connection refused error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.
Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.
Follow these steps to make sure:
Open "Sql Server Configuration Manager" in "Start Menu\Programs\Microsoft SQL Server 2012\Configuration Tools\"
Expand "SQL Server Network Configuration"
Go in "Protocols for SQLEXPRESS"
Enable TCP/IP
If you have any problem, check this blog post for details, as it contains screenshots and much more info.
Also check if the "SQL Server Browser" windows service is activated and running:
Go to Control Panel -> Administrative Tools -> Services
Open "SQL Server Browser" service and enable it (make it manual or automatic, depends on your needs)
Start it.
That's it.
After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.
Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JtdsSqlExpressInstanceConnect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "user";
String password = "password";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}
And if you use Maven, add this to your pom.xml:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
jdbc:jtds:sqlserver://x.x.x.x/database replacing x.x.x.x with the IP or hostname of your SQL Server machine.
jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS
or
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
If you are wanting to set the username and password in the connection string too instead of against a connection object separately:
jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS;user=foo;password=bar
(Updated my incorrect information and add reference to the instance syntax)
A shot in the dark, but
From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port
SQLServer runs the default instance over port 1433. If you specify the port as port 1433, SQLServer will only look for the default instance. The name of the default instance was created at setup and usually is SQLEXPRESSxxx_xx_ENU.
The instance name also matches the folder name created in Program Files -> Microsoft SQL Server. So if you look there and see one folder named SQLEXPRESSxxx_xx_ENU it is the default instance.
Folders named MSSQL12.myInstanceName (for SQLServer 2012) are named instances in SQL Server and are not accessed via port 1433.
So if your program is accessing a default instance in the database, specify port 1433, and you may not need to specify the instance name.
If your program is accessing a named instance (not the default instance) in the database DO NOT specify the port but you must specify the instance name.
I hope this clarifies some of the confusion emanating from the errors above.

Categories