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.......:)
Related
Original Post ~
I am trying to send an email through java but I am getting an error that says it couldn't connect to host, port: smtp.gmail.com, 547; timeout -1;
I am trying to send it through gmail and I have imported two jar files, which are java mail api download – https://javaee.github.io/javamail/ java activation jar download – https://mvnrepository.com/artifact/javax.activation/activation/1.1.1
It takes forever to run and once it finally does finish it show that error.I would appreciate any help, even if it is just pointing me to a YouTube video or another post on this website. Thank you in advance.
Updated Post~
I had a comment saying to use 587 instead of 547 so I changed it but I am now getting an javax.mail.AuthenticationFailedException: Username and password not accepted error. I have googled and even looked on stack overflow and they say to change a setting in my google account but when I go to change it google is saying the setting is no longer available... it is the Less Secure app access.
I will love any thoughts or direction on how to fix this problem. I am on a Mac if anyone thinks that could be causing a problem.
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Properties;
public class Mail {
Session newSession = null;
MimeMultipart multiPart = new MimeMultipart();
MimeMessage mimeMessage = new MimeMessage(newSession);
public static void main(String[] args) throws MessagingException, IOException, AddressException {
Mail mail = new Mail();
mail.setupServerProperties();
mail.draftEmail();
mail.sendEmail();
}
private void setupServerProperties() {
Properties properties = System.getProperties();
properties.put("mail.smtp.port", "587"); //was 547 changed // to 587
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
newSession = Session.getDefaultInstance(properties, null);
}
private MimeMessage draftEmail() throws AddressException, MessagingException, IOException {
String[] emailRecipients = {"abcd#gmail.com", "abcde#gmail.com"}; //who it is going to
String emailSubject = "Test Mail";
String emailBody = "Test body of email";
for(int i =0; i< emailRecipients.length; i++ ){
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailRecipients[i]));
System.out.println("This is i" + i);
}
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(emailBody, "html/text");
multiPart.addBodyPart(bodyPart);
mimeMessage.setContent(multiPart);
return mimeMessage;
}
private void sendEmail() throws MessagingException{
String fromUser = "yourPersonalEmail#gmail.com"; //sender
String fromUserPassword = "yourPassword"; //Password for senders email
String emailHost = "smtp.gmail.com";
Transport transport = newSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
System.out.println("Email Successfully sent");
}
}
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
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
}
});
I am trying to connect to locally hosted email POP3 inbox and display emails in the mailbox, but I keep getting error:
Exception in thread "main" javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.kami.utils.MailClient.checkInbox(MailClient.java:33)
at com.kami.Main.main(Main.java:38)
My class looks like this:
public class MailClient {
private String host;
private String username;
private String password;
private String provider;
protected Session session;
public MailClient() {
Properties props = new Properties();
this.host = "localhost";
this.username = "unix-user";
this.password = "unix-password";
this.provider = "pop3";
this.session = Session.getDefaultInstance(props, null);
}
public void checkInbox() throws MessagingException, IOException {
Store store = session.getStore(provider);
store.connect(host, username, password); //This is line 33
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for(Message message : messages){
System.out.println(message.getReceivedDate());
System.out.println(message.getSubject());
}
inbox.close(true);
store.close();
}
}
It is locally hosted email server using Dovecot IMAP/POP3 Server Version 2.2.9 and Postfix Mail Server Postfix version 2.11.0
First telnet 110 port in your machine to check if the service is running there. In my laptop i don't have a pop3 server running, and this is the result:
hans#andes:~$ telnet localhost 110
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
If the connection succeed, follow the protocol authentication of pop3 with your own data:
hans#andes:~$ telnet mail.foo.com 110
Trying X.X.X.X...
Connected to mail.foo.com.
Escape character is '^]'.
+OK mail.foo.com POP3 server ready
user fooUser
+OK hello fooUser, please enter your password
pass fooPassword
+OK server ready
In your case telnet localhost; note too that you only should issue the commands: telnet, user and pass. The rest is the response from the server.
If all this works, the problem is on something with your java configuration, check the documentation and samples from the library.
The below method will fetch messages from a pop mailbox (given _Host=localhost, _User=unix-user, _Password=unix-password, _Protocol="pop3"). However you must be sure of a few things:
1) "localhost" is running a "pop3" server and not a "pop3s" (secure protocol) server;
2) the "pop3" server on "localhost" is listening on the default port
3) "unix-user" has a pop3 mailbox
Based on your follow-up, it seems like you are expecting to be able to send mail from the pop3 account. This is not how it works as pop3 is only a way to retrieve messages, not send them. To send mail, you need to establish a separate connection to an SMTP server.
public Message[] getMessages(int maxCount)
throws MessagingException
{
// Get a Session object
Properties props = new Properties();
Session session = Session.getInstance(props);
// Get a Store object
Store store = session.getStore(_protocol);
// Connect
store.connect(_host,_user,_password);
// Open a Folder
Folder folder = store.getFolder(_mailbox);
if (folder == null || !folder.exists())
throw new ApplicationException("Invalid mailbox");
//Gets up to maxCount messages from the pop box
folder.open(Folder.READ_WRITE);
Message[] messages = Monitor.EMPTY_MESSAGE_ARRAY;
int toMessageIndex=folder.getMessageCount();
if (toMessageIndex > 0) {
if (toMessageIndex > maxCount)
toMessageIndex = maxCount;
messages = folder.getMessages(1,toMessageIndex);
}
// Go through all the new messages and make sure they are loaded. Use the outputStream
//to force all information to be downloaded.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (int i = 0; i < messages.length && shouldRun(); i++) {
try {
//Force the download of all message information
bos.reset();
messages[i].writeTo(bos);
getLog().enter(
this,
"[readAndClearInBox] Read message to " + messages[i].getAllRecipients()[0].toString());
} catch (Exception mex) {
getLog().error(this, mex, "[readAndClearInBox] Message exception");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
try {
Monitor.dumpEnvelope(getLog(), pw, messages[i]);
} catch (Exception ex) {
getLog().error(this, mex, "[readAndClearInBox] Could only display faulty message.");
} finally {
pw.flush();
getLog().enter(this, "[readAndClearInBox]" + sw.toString());
}
} finally {
//Mark the message for deletion
messages[i].setFlag(Flags.Flag.DELETED, true);
}
}
//Close folder and expunge all deleted messages, unless the read was aborted
if (shouldRun()) {
getLog().enter(this,"Found " + messages.length + " messages; closing inbox.");
folder.close(true);
store.close();
return messages;
} else {
getLog().enter(this,"Found " + messages.length + " messages; closing inbox without expunging.");
folder.close(false);
store.close();
_bShouldRun = true;
return Monitor.EMPTY_MESSAGE_ARRAY;
}
}
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.