Sending an email using Google's SMTP server - email

I'm having a trouble sending an email using Google's SMTP Server. I've looked for a solution but i have not found one. So here's the code.
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
...
...
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
Properties props = new Properties();
props.put("true", "mail.smtp.auth");
props.put("true","mail.smtp.starttls.enable");
props.put("smtp.gmail.com", "mail.smtp.host");
props.put("587", "mail.smtp.port");
Session sess=Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("myemail#gmail.com", "mypassword");
}
}
);
try{
Message message= new MimeMessage(sess);
message.setFrom(new InternetAddress("myemail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("myemail#gmail.com"));
message.setSubject("message");
message.setText("text");
Transport.send(message);
JOptionPane.showMessageDialog(null, "Sent!");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
Each time when i press the button, it show me this error:
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
I've tried 3 ports: 25, 465, 587 , but it always gives me that error. I even made new rules for the port 25 to the firewall settings, but that doesn't seem to do the trick. Any thoughts what am i doing wrong? Could hibernate cause the problem? Because i'm using it in this project. Plus, i have installed mysql.

Your program is trying to connect to a local port, that's why it failed. If your listing is real code, you got the key and value backwards in the props.set statements.

Related

MailKit - smtp.Connect throw exception in C# .Net

Exception while connecting to the server: A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond.
1.) able to ping the server
2.) telnet smtp.office365.com 587 respond as expected.
public ConnectSmtpServer()
{
using MailKit.Net.Smtp;
string _SmtpServer = "smtp.office365.com";
int _portNumber = 587;
Console.WriteLine("Welcome!");
using (SmtpClient smtp = new SmtpClient())
{
try
{
smtp.Timeout = 30 * 1000;
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine("Test smtp connection using MailKit.Net !");
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine();
}
}
}

IAm using InetAddress to get server IP but it resolves to local host because my server name is same as server IP, what should I do?

I am using following code to connect Jmeter to a remote mongo DB with authentication. I am using InetAddress to get server IP but it resolves to local host because my server name is same as server IP, what alternative should I use?
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
try {
String mongoUser = vars.get("mongouser");
String userDB = vars.get("userdb");
char[] password = vars.get("password").toCharArray();
MongoCredential credential = MongoCredential.createCredential(mongoUser,
userDB, password);
MongoClientSettings settings = MongoClientSettings.builder()
.applyToClusterSettings {builder ->
builder.hosts(Arrays.asList(new
ServerAddress(InetAddress.getByName(vars.get("mongohost"))
,vars.get("mongoPort").toInteger())))}
.build();
MongoClient mongoClient = MongoClients.create(settings);
MongoDatabase database = mongoClient.getDatabase(vars.get("databaseName"));
MongoCollection<Document> collection = database.getCollection(vars.get("collectionName"));
vars.putObject("collection", collection);
return "Connected to " + vars.get("collectionName");
}
catch (Exception e) {
SampleResult.setSuccessful(false);
SampleResult.setResponseCode("500");
SampleResult.setResponseMessage("Exception: " + e);
}
Iam getting following error which shows that InetAdress is not resolving my mongo host name (which is same as Mongo host IP i-e 10.80.47.101)
Response code: 500
Response message: Exception: com.mongodb.MongoTimeoutException: Timed out
after 30000 ms while waiting to connect. Client view of cluster state is
{type=UNKNOWN, servers=[{address=ibexdc1v-dbdev10.corp.ibexglobal.com:27002,
type=UNKNOWN, state=CONNECTING, exception=
{com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by
{java.net.ConnectException: Connection refused: connect}}]
If ibexdc1v-dbdev10.corp.ibexglobal.com is correct hostname for your mongohost JMeter Variable you check whether MongoDB instances is listening on port 27002 and ensure that the port is open in your operating system firewall
If ibexdc1v-dbdev10.corp.ibexglobal.com is not correct hostname for your mongohost JMeter Variable you should fix your machine DNS configuration
You can explicitly specify the hostname by slightly amending your script, i.e. change this line:
builder.hosts(Arrays.asList(new ServerAddress(InetAddress.getByName(vars.get("mongohost")), vars.get("mongoPort").toInteger())))
to this one:
builder.hosts(Collections.singletonList(new ServerAddress(vars.get("mongohost"), vars.get("mongoPort") as int)))
You might also be interested in the MongoDB Performance Testing with JMeter article

Getting the JavaMail API to Work... Again

I'm working on an application that uses the JavaMail API to send an email, but I keep getting errors. I'm using Eclipse to code it and I'm using gmail to send it. I took out my real password for obvious reasons so you're probably going to need to replace that with your own if you need to experiment. Now that I've fixed some stuff thanks to you guys, I think I'm getting a timeout error because it takes a long time until it displays the error, but beyond that much, I haven't the foggiest clue. Thanks in advance for any help or advice once more.
Code:
package com.brighamcampbell.sunrisegundersonmail;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class Mail {
public static void main(String[] args) throws MessagingException,
UnsupportedEncodingException {
Properties mailProps = new Properties();
mailProps.put("mail.smtp.from", "butterscotchdreamer23#gmail.com");
mailProps.put("mail.smtp.host", "smtp.gmail.com");
mailProps.put("mail.smtp.ssl.trust", "smtp.gmail.com");
mailProps.put("mail.smtp.port", "465");
mailProps.put("mail.smtp.auth", true);
mailProps.put("mail.smtp.starttls.enable", "true");
Session mailSession = Session.getDefaultInstance(mailProps, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("butterscotchdreamer23#gmail.com", "password");
}
});
MimeMessage message = new MimeMessage(mailSession);
//set the email sender
message.setFrom(new InternetAddress("butterscotchdreamer23#gmail.com"));
//set the email recipients
String[] emails = { "butterscotchdreamer23#gmail.com" };
InternetAddress dests[] = new InternetAddress[emails.length];
for (int i = 0; i < emails.length; i++) {
dests[i] = new InternetAddress(emails[i].trim().toLowerCase());
}
message.setRecipients(Message.RecipientType.TO, dests);
//set the email subject
message.setSubject("test");
//set the email content
message.setText("this is a test");
//send
System.out.println("sending...");
Transport.send(message);
System.out.println("done sending email!");
}
}
Error:
Exception in thread "main" 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:2041)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at com.brighamcampbell.sunrisegundersonmail.Mail.main(Mail.java:56)
Thanks for the patience!
Clearly the mail server doesn't support STARTTLS, so you shouldn't enable it.
Try removing the 3 sslfactory properties as it is not needed anymore for javamail.You should be able to connect that way.
Note:The gmail server definitely support STARTTLS:
x#test:~/$ telnet smtp.gmail.com 587
Trying 74.125.136.108...
Connected to gmail-smtp-msa.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP vv9sm12826892wjc.35 - gsmtp
EHLO me
250-mx.google.com at your service, [147.58.51.121]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
QUIT
General Gmail instructions are here, general connection debugging tips are here, and a list of common mistakes is here. Possibly you're running into a firewall or anti-virus program that's intercepting your attempt to connect. If you still can't make it work, post the JavaMail debug output.

Error while connecting to openfire server using asmack 4.0.2

Im trying to connect to Openfire Server using Asmack library 4.0.2.Im failing to get connected to the server even though i had provided correct ip address with the port.
public static final String HOST = "192.168.1.100";
public static final int PORT = 9090;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connect();
}
public void connect(){
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... arg0){
boolean isConnected = false;
ConnectionConfiguration config = new ConnectionConfiguration(HOST,PORT);
config.setReconnectionAllowed(true);
config.setSecurityMode(SecurityMode.disabled);
config.setDebuggerEnabled(true);
XMPPConnection connection = new XMPPTCPConnection(config);
try{
connection.connect();
Log.i("XMPPChatDemoActivity","Connected to " + connection.getHost());
isConnected = true;
} catch (IOException e){
Log.e("XMPPIOExceptionj", e.toString());
} catch (SmackException e){
Log.e("XMPPSmackException", e.toString()+" Host:"+connection.getHost()+"Port:"+connection.getPort());
} catch (XMPPException e){
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ connection.getHost());
Log.e("XMPPChatDemoActivity", e.toString());
}
return isConnected;
}
};
connectionThread.execute();
}
And im getting the following error possibly because Host and Port are getting assigned null and 0 respectively even though i had assigned them correctly.Pls help me in
sorting out this connection prob.
08-12 22:10:20.496: E/XMPPSmackException(4341):org.jivesoftware.smack.SmackException$NoResponseException Host:nullPort:0
Can you confirm that port 9090 is the correct port for XMPP protocol? Default install of Openfire will set port 9090 to be used for accessing the HTTP based configuration console. I recommend you try connecting to the port for XMPP connections as specified on the main index page of the Openfire configuration console (Listed below "Server Ports").
The following is taken from the Openfire configuration console:
5222 The standard port for clients to connect to the server. Connections may or may not be encrypted. You can update the security settings for this port.
I think your Host adress is wrong too, you must use the adress to connect openfire server. It must be "127.0.0.1" or just write "localhost". and the port is 5222 to be able to talk from client to server.

Jersey Grizzly REST service not visible outside localhost

I'm trying to write a REST service in java using Jersey and Glassfish Grizzly. I have a very simple case working internally, but can't seem to call on the server from an external address. I've tried using a variety of different pairs of machines with externally visible IP's, and tried specifying the actual IP address in the server instead of localhost, but nothing works. I'm somewhat loosely following the official user guide here. My resource:
package resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/simpleREST")
public class SimpleRESTResource
{
#GET
#Produces("text/plain")
public String getMessage()
{
return "Message from server\n";
}
}
And the server:
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class Main
{
public static final URI BASE_URI = UriBuilder.fromUri("http://localhost").port(9998).build();
public static void main(String[] args) throws IOException
{
System.out.println("Starting grizzly...");
ResourceConfig rc = new PackagesResourceConfig("resources");
HttpServer myServer = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
System.out.println(String.format("Jersey app started with WADL available at %s/application.wadl\n" +
"Try out %s/simpleREST\nHit enter to stop it...", BASE_URI, BASE_URI));
System.in.read();
myServer.stop();
}
}
On the same machine, I can successfully interact with the server using
curl -X GET localhost:9998/simpleREST
OR
curl -X GET [external numeric address]:9998/simpleREST
Many thanks in advance for any suggestions.
SOLUTION
I have fixed this problem by setting the server URI to http://0.0.0.0:9998 instead of localhost, 127.0.0.1, or the actual address.
To make a server IP adress visible outside of localhost, you must fist open the neccessary firewall ports(if you have one), or use "0.0.0.0" instead of "localhost" in order for the server to listen to all IP addresses and network adapters. Before testing it in your local network, try pinging your server device from your client device to check if there is an actual connection or if the devices are not connected at all.
With Jersey and Grizzly 2.30, it's simpler:
final ResourceConfig rc = new ResourceConfig().packages("com.rest");
HttpServer httpServer = Grizzly
HttpServerFactory.createHttpServer(URI.create("http://0.0.0.0:9998/api/"), rc);
or, you can try these codes below:
ResourceConfig rc = new PackagesResourceConfig("your-rest-packages");
HttpHandler handler = ContainerFactory.createContainer(HttpHandler.class, rc);
server = new HttpServer();
server.getServerConfiguration().addHttpHandler(handler);
//attach listeners
InetAddress localHost = InetAddress.getLocalHost();
String localHostAddr = localHost.getHostAddress();
NetworkListener localHostListener = new NetworkListener("localhost", localHostAddr, port);
server.addListener(localHostListener);
InetAddress loopback = InetAddress.getLoopbackAddress();
String loopbackAddr = loopback.getHostAddress();
NetworkListener loopbackListener = new NetworkListener("loopback", loopbackAddr, port);
now your server could both list to localhost and loopback