Java Mail not working suddenly - java

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

Related

How to send email to Microsoft direct send (domain-com.mail.protection.outlook.com) using groovy, java

I am trying to send email to user#domain.com via domain-com.mail.protection.outlook.com (Office 365 direct send),
below is my code,
void sendEmail(InternetAddress sender, List<InternetAddress> recipients, String subject, String body,
#Nullable BodyPart optAttachment,
XgemailDirectionEnum direction = XgemailDirectionEnum.INBOUND,
Optional<String> optionalEnvelopeSenderAddress = Optional.empty())
{
final Properties properties = new Properties(_defaultProperties)
for (InternetAddress recipient : recipients)
{
if (optionalEnvelopeSenderAddress.isPresent())
{
properties.put("mail.smtp.from", optionalEnvelopeSenderAddress.get())
}
Session session
properties.put("mail.smtp.host", domain-com.mail.protection.outlook.com)
properties.put("mail.smtp.port", 25)
properties.put("mail.debug", "true")
session = Session.getInstance(properties)
Message message = new MimeMessage(session)
message.setFrom(sender)
message.setRecipients(
Message.RecipientType.TO,
recipient as InternetAddress[]
)
message.setSubject(subject)
message.setText(body)
Transport.send(message)
}
I tried adding properties properties.put("mail.smtp.starttls.enable", "true") also, but no luck.
I am getting following error
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: domain-com.mail.protection.outlook.com, 25; timeout -1
Following is mail.debug log
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false DEBUG SMTP: trying to connect to host "domain-com.mail.protection.outlook.com", port 25, isSSL false

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
}
});

Unable to send gmail mail

I am trying to write a java code to send an email via Gmail , I was able to get the correct configuration and code, and have tested my code at home, (email was sent successfully from home), problems appear when I run the same code at work, I was able to figure out the problem is on the network, so I asked my NW admin to open ports 465 and 587 for me and start facing a new issue that I am unable to establish a connection with smtp.gmail.com on both ports , I installed telnet, and run the following command
telnet smtp.gmail.com 465
and the telnet connection is acting in such a weird way (command shows only underscore (_) and nothing appears, see attached image), note that when I run the same command on any other machine at work it runs fine.
I turned off windows firewall, anti-virus . and still unable to determine what I need to do to get it works since the issue is only my PC.
here is my code:
package mail;
private SendMail() {
}
public static void main(String[] args) throws AddressException, MessagingException {
try {
send("mySenderMail#gmail.com", "myPassword", "myRecieverMail#gmail.com", "test java code mail", "this is a text message string");
System.out.println("Sent Sucessfully");
}
catch (AddressException exc) {
System.out.println("exception"+ exc.getMessage());
System.out.println("cause:"+ exc.getCause());
}
catch(MessagingException exc ){
System.out.println("exception"+ exc.getMessage());
System.out.println("cause:"+ exc.getCause());
}
catch(Exception exc){
System.out.println("exception"+ exc.getMessage());
System.out.println("cause:"+ exc.getCause());
}
}
public static void send(final String username, final String password, String recipientEmail, String title,
String message) throws AddressException, MessagingException,ArrayIndexOutOfBoundsException , IOException {
SendMail.send(username, password, recipientEmail, "", title, message);
}
public static void send(final String username, final String password, String recipientEmail, String ccEmail,
String title, String message) throws AddressException, MessagingException , ArrayIndexOutOfBoundsException, IOException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// Get a Properties object
String emailHost = username.split("#")[1].toLowerCase() + ".";
Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("mail/mailConfig.properties");
prop.load(stream);
String smtpHost = prop.getProperty(emailHost + "smtpHost");
String socketFactoryClass = prop.getProperty(emailHost + "socketFactoryClass");
String socketFactoryFallback = prop.getProperty(emailHost + "socketFactoryFallback");
String smtpPort = prop.getProperty(emailHost + "smtpPort");
String socketFactoryPort = prop.getProperty(emailHost + "socketFactoryPort");
String auth = prop.getProperty(emailHost + "auth");
String starttlsEnable = prop.getProperty(emailHost + "starttlsEnable");
String debug = prop.getProperty(emailHost + "debug");
String quitwait = prop.getProperty(emailHost + "quitwait");
Properties props = System.getProperties();
if (smtpHost != null && !smtpHost.isEmpty())
props.setProperty("mail.smtp.host", smtpHost);
if (socketFactoryClass != null && !socketFactoryClass.isEmpty())
props.setProperty("mail.smtp.socketFactory.class", socketFactoryClass);
if (socketFactoryFallback != null && !socketFactoryFallback.isEmpty())
props.setProperty("mail.smtp.socketFactory.fallback", socketFactoryFallback);
if (smtpPort != null && !smtpPort.isEmpty())
props.setProperty("mail.smtp.port", smtpPort);
if (socketFactoryPort != null && !socketFactoryPort.isEmpty())
props.setProperty("mail.smtp.socketFactory.port", socketFactoryPort);
if (auth != null && !auth.isEmpty())
props.setProperty("mail.smtp.auth", auth);
if (starttlsEnable != null && !starttlsEnable.isEmpty())
props.setProperty("mail.smtp.starttls.enable", starttlsEnable);
if (debug != null && !debug.isEmpty())
props.setProperty("mail.smtp.debug", debug);
if (quitwait != null && !quitwait.isEmpty())
props.put("mail.smtps.quitwait", quitwait);
Session session = Session.getInstance(props, null);
// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);
session.setDebug(true);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));
if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}
msg.setSubject(title);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());
SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
t.connect(smtpHost, username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
}
and here is my configuration file contents :
## ----------------- Gmail -----------------##
gmail.com.smtpHost = smtp.gmail.com
gmail.com.socketFactoryClass = javax.net.ssl.SSLSocketFactory
gmail.com.socketFactoryFallback = false
gmail.com.smtpPort = 465
gmail.com.socketFactoryPort = 465
gmail.com.auth = true
gmail.com.starttlsEnable = true
gmail.com.debug = true
gmail.com.quitwait = false
telnet image
btw: I have got the following exception when I run my code
DEBUG: setDebug: JavaMail version 1.4.5
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
Exception in thread "main" 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:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at mail.SendMail.send(SendMail.java:213)
at mail.SendMail.send(SendMail.java:111)
at mail.SendMail.main(SendMail.java:26)
Caused by: 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.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:207)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
I really don't know what I have to do next, please help.
I've not tested this yet since i'm in an enclosed environment but I suppose what you're trying to do here is keeping the connection as TLS while using port which is used for SSL.
As per the gmail specification, they use port-465 for SSL while port-587 for TLS.
Try either of below:
gmail.com.smtpPort = 587
or
gmail.com.starttlsEnable = false
Hope this helps.......:)

Failed to send Mail with Javax.mail

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.

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.

Categories