Failed to send Mail with Javax.mail - java

I'm trying to send an email on Windows 8.1 with java 1.8 using javax.mail API but I keep getting an error.
Here is the method I wrote:
public void sendAlertMail(String from, String to, String header, String msgBody){
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", smptHost);
props.put("mail.smtp.port", smptPort);
props.put("mail.smtp.starttls","true");
Session mailSession;
if (authenticate) {
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
mailSession = Session.getInstance(props, auth);
}
else{
mailSession = Session.getInstance(props);
}
// uncomment for debugging infos to stdout
// mailSession.setDebug(true);
Transport transport = null;
try {
transport = mailSession.getTransport();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
MimeMessage message = new MimeMessage(mailSession);
try {
message.addHeaderLine(header);
message.setContent(msgBody, "text/plain");
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
} catch (MessagingException e) {
}
try {
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
And the error I receive is:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2100)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:699)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at tapperSolution.mail.MailSender.sendAlertMail(MailSender.java:64)
at tapperSolution.mail.MailSender.sendAlertMail(MailSender.java:74)
at tapperSolution.mail.MailSender.main(MailSender.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.net.SocketException: Permission denied: connect\at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2066)
... 12 more
I turned off my firewall and anti virus and I tried to set the VM option in my code using:
System.setProperty("java.net.preferIPv4Stack", "true");
Also tried to set it in the run command with:
-Djava.net.preferIPv4stack=true
I was able to send mail using Python, but I want to do it using Java.
Tried to capture traffic using Wireshark, but there is no even a TCP handshake with the server.
Any other ideas?
Thanks

It looks like your SMTP server may be rejecting your connection, perhaps due to authentication issues. To test this, try a manual SMTP session from the same machine, and see what the result is.

Related

sending e-mails automatically

I'm trying to setup a program which can automatically send e-mails. However, the first step doesn't even work for me and it gives this error:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: 127.0.0.1, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at server.main(server.java:46)
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.base/java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
at java.base/java.net.PlainSocketImpl.connect(PlainSocketImpl.java:148)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
at java.base/java.net.Socket.connect(Socket.java:591)
at java.base/java.net.Socket.connect(Socket.java:540)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:239)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 7 more
This is the code:
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class server {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "my other email properly written";
// Sender's email ID needs to be mentioned
String from = "my email properly written";
// Assuming you are sending email from localhost
String host = "127.0.0.1";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Does anyone have any idea why this happens and how to solve this? My e-mail is actually open etc. And because it's localhost I have no idea why it wouldn't work.
Access to a SMTP server would require the smtp host port and the security settings if applicable.
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "hostname") #
props.put("mail.smtp.port", "portnumber") #25
props.put("mail.smtp.starttls.enable", "boolean value true or false")
props.put("mail.smtp.auth", "boolean value true or false")
Usually a session need to be created (a Java mail session using the username and password and the properties), that is missing in the code above. For demonstration purpose,
Session session = javax.mail.Session.getInstance( props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication("username", "password"); //username and password
}
});

Java Mail not working suddenly

Java mail code was working, now it suddenly doesn't work at all!
What changed? What's wrong with the code?
private static void testRaw(){
//<editor-fold defaultstate="collapsed" desc="code">
String host = "smtp.hotmail.com";
int port = 587;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.port", 587);
properties.setProperty("mail.transport.protocol", smtp);
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
}
);
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("test title");
message.setText("test message");
Transport transport = session.getTransport("smtp");
transport.connect(host, port, from, password);
transport.send(message);
System.out.println("Send OK");
} catch (Exception e) {
e.printStackTrace();
}
//</editor-fold>
}
The following are the prints:
DEBUG: setDebug: JavaMail version 1.5.5
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.live.com", port 587, isSSL true
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.live.com, 587; timeout -1;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2100)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:699)
at javax.mail.Service.connect(Service.java:366)
at email.v2.Test.testRaw(Test.java:135)
at email.v2.Test.main(Test.java:41)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:331)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2066)
What's wrong with the code and how do I fix it?
Port 587 does not work with hotmail. You have to use 25 or 465.
Also change your host to smtp.live.com
Have a look here

Connecting to IMAP javax.net.ssl.SSLException: Unrecognized SSL message

I am trying to connect to my company IMAP server using following program but I am getting SSLException.
import javax.mail.*;
import java.util.Properties;
/**
* Created by SDuraisamy on 6/18/2014.
*/
public class Test {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, null);
Store store = null;
try {
store = session.getStore();
// store.connect("imap.gmail.com","mygmailaccount#gmail.com","password");
store.connect("exchange_server", "account2", "password");
Folder inbox = store.getFolder("INBOX");
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
I am getting following Exception
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at Test.main(Test.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(InputRecord.java:523)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:355)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789)
How can I resolve this error?
The same code works when I connect to my gmail account(source commented above), I am able to connect and read messages through my program.
Any setting required at exchange server end to download messages through IMAP? I already have IMAP enabled on my exchange server.
Changing
props.setProperty("mail.store.protocol", "imaps");
to
props.setProperty("mail.store.protocol", "imap");
resolved the issue

Can't connect to Hotmail with JavaMail

First, let me appoligize if this is a duplicate question. Over the last couple of calendar months, I have been attempting to send email, using JavaMail; via my Hotmail account. I have used the numerious tips and code snipits that have been posted to this site in the past on this topic; however, I am still getting a java.net.ConnectException: Connection refused... when I execute the Transport.connect method
Here's my code
String fromUserName = "testEmailAddress#hotmail.com";
String fromEMailAddress = "My Email Test <testEmailAddress#hotmail.com>";
String fromEmailPassword = "testEmailPassword";
String emailServerName = "smtp.live.com";
String emailServerPort = "587";
String toEMailAddress = "<TestDestinationEmailAddress#gmail.com>";
Properties emailProps = System.getProperties();
emailProps.put("mail.smtps.host", emailServerName);
emailProps.put("mail.smtps.auth", "true");
emailProps.put("mail.transport.protocol", "smtps");
emailProps.put("mail.smtps.starttls.enable", "true");
emailProps.put("mail.smtps.ssl.enable","true");
emailProps.put("mail.smtps.port", emailServerPort);
emailProps.put("mail.debug", "true");
Authenticator localAuthenticator = new SMTPAuthenticator(fromUserName, fromEmailPassword);
Session emailSession = Session.getInstance(emailProps, localAuthenticator);
try {
SMTPTransport emTransport = (SMTPTransport) emailSession.getTransport("smtps");
emTransport.connect(emailServerName, Integer.parseInt(emailServerPort), fromUserName, fromEmailPassword);
System.out.println("Ok, we connected ok.");
MimeMessage emailMsg = new MimeMessage(emailSession);
emailMsg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEMailAddress));
emailMsg.setFrom(new InternetAddress(fromEMailAddress));
emailMsg.setSubject("Automated Notification Number 1");
emailMsg.setContent(getHtmlContent(), "text/html");
emTransport.sendMessage(emailMsg, emailMsg.getAllRecipients());
System.out.println("Sent Message#: 1");
} catch (Exception e) {
e.printStackTrace();
}
And here's the exception...
DEBUG JavaMail version 1.4.5
DEBUG successfully loaded resource: /META-INF/javamail.default.providers
DEBUG SMTP useEhlo true, useAuth true
DEBUG SMTP trying to connect to host "smtp.live.com", port 587, isSSL true
javax.mail.MessagingException: Could not connect to SMTP host: smtp.live.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: 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:295)
at com.acf.TestingClasses.EmailSendingGames.sendMail(Unknown Source)
at com.acf.TestingClasses.EmailSendingGames.main(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
A couple of things:
I have tried both "smtp" and "smtps"...it doesn't seem to matter
I have tried ports: 25, 465, 587, and 995...still refuses the connection
I have tried the code on many computers with the same results.
Cut-and-pasted the code from the JavaMail demo code but stll get the error.
The code works for yahoo, at&t, gmail, and others...but not Hotmail!
I removed all the "socketFactory" stuff, as in Using javamail to send from hotmail?
Then it worked fine...
Below is the function:
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", _host);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", _port);
return props;
}
Presumably you've already read this JavaMail FAQ entry.
Did you also try the debugging tips here?
From the debug output you posted, it looks like you have a firewall or something that's preventing you from connecting to that site.

Unable to read the Gmail INBOX from the java code using POP API .. giving an error java.net.ConnectException: Connection timed out: connect error

props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", "xxx#gmail.com");
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props,
new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxx",
"xxx");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", "xxxxx", "xxx");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.HOLDS_MESSAGES);
int count = fldr.getMessageCount();
System.out.println(count);
} catch (Exception exc) {
System.out.println(exc + " error");
}
// TODO Auto-generated method stub
}
Error:
javax.mail.MessagingException: Connect failed; nested exception is: java.net.ConnectException: Connection timed out: connect error
As I have added Proxy setting in this application
And set firewalls off. Still its is giving the above error.
The JavaMail FAQ has simpler code for connecting to Gmail, as well as tips for debugging connection problems and instructions for using proxy servers.

Categories