Sending emails over SMTP with TSL - java

The code posted below works fine for me to send an email over an STMP with SSL.
Now the SMTP changed to TSL and i dont manage to send email with it.
I tried several things like adding
props.put("mail.smtp.starttls.enable","true");
but it was no use.
The error code says:
"javax.mail.MessagingException: Could not connect to SMTP host: exch.studi.fhws.de, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?"
Any ideas?
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
String d_email = "...",
password = "...",
host = "...",
port = "25",
mailTo = "...",
mailSubject = "test",
mailText = "test";
public SendMail()
{
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(mailText);
msg.setSubject(mailSubject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
Transport.send(msg);
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public static void main(String[] args)
{
TextClass tc = new TextClass();
}
private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(d_email, password);
}
}
}

The error message says you're connecting to port 587 - this is an SSL-enabled email port, which means the connection has to be SSL from the get-go. Your code is connecting via plaintext (e.g. plain port 25) and THEN attempting to start TLS. This won't work, as port 587 expects an SSL exchange immediately, not a "EHLO ... / STARTTLS" plaintext command set.

Maybe this answer, talking about Exchange servers with SMTP ports disabled, is useful: https://stackoverflow.com/a/12631772/187148

Related

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 578;

I am new in Java. I want to build an application which will send email to my clients. I searched over stackoverflow but didn't get any desired solution for that. Somewhere I saw that this could be an issue of firewall but didn't get the solution for fixing it.
I am using Ubuntu 14.10
//Here is my code.
public class sendMail {
public void send(String from, String to, String subject, String body) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxxx#gmail.com","xxxxx");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xxxxxx#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("xxxx#domain.com"));
message.setSubject("Testing Subject");
message.setText("Hello this is not spam," +
"\n\n This is a JavaMail test...!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
And my Error is:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out
at dbdemo.sendMail.send(sendMail.java:54)
at dbdemo.DBDemo.main(DBDemo.java:62)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:313)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at dbdemo.sendMail.send(sendMail.java:49)
... 1 more
Caused by: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
... 8 more
Java Result: 1
Any help would be appreciated. Please help me.
Throw away the code that you cut and pasted from someone who doesn't understand how to use JavaMail and use the code for connecting to Gmail in the JavaMail FAQ.
If it doesn't work for you, follow the debugging tips in the JavaMail FAQ.
If you still can't figure it out, and can't find the answer in the JavaMail FAQ, post the JavaMail debug output here.
This code worked for me,
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "xxxx"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "xxxx"; // GMail password
private static String RECIPIENT = "xxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
// String host="localhost";
// props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
// props.put("mail.smtp.host", host);
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");//587
props.put("mail.smtp.auth", "true");
//System.out.println("success point 1");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
//System.out.println("success point 2");
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
//System.out.println("success point 3");
message.setSubject(subject);
message.setText(body);
// System.out.println("success point 4");
Transport transport = session.getTransport("smtp");
// System.out.println("success point 5");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
//System.out.println("success 6");
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
And i had used some jar files are
activation,java-mail-1.4.4,javamail-smtp-1.4.2,pop3,mail-6.0.0-sources
Connection timeouts typically result from
some kind of firewall on the way that simply eats the packets
without telling the sender things like "No Route to host"
packet loss due to wrong network configuration or line overload
too many requests overloading the server
Here is How do I turn off firewall on Ubuntu
If that doesn't work try Changing the props.put("mail.smtp.port", "587"); to props.put("mail.smtp.port", "465"); or props.put("mail.smtp.port", "25");
Some further info (not timeout related), once you're connected:
Don't forgot to Double check your login credentials. because they may cause Authentication Failed Exception if provided incorrect

Error when sending mail in Java

i have desktop application and i face this error when sending mail javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection refused: connect
~code~
String host="smtp.mail.yahoo.com";
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host",host);
props.put("mail.smtp.host", host);
props.put("mail.stmp.user", "abc#yahoo.ca");//User name
//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "mypassword"); //Password
props.put("mail.smtp.socketFactory.fallback", "false");
Session session1 = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "abc#yahoo.ca";
String password = "mypassword";
return new PasswordAuthentication(username, password);
}
});
MimeMessage msg = new MimeMessage(session1);
String from = "abc#yahoo.ca";
String subject = "Testing...";
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
msg.setSubject(subject);
Transport.send(msg);
YahooMail smtp port is 465 or 587
Add this :-
props.put("mail.smtp.port", "465");
or
props.put("mail.smtp.port", "587");
Did you find the JavaMail FAQ?
These entries will help:
How do I access Gmail with JavaMail?
How do I debug problems connecting to my mail server?
What are some of the most common mistakes people make when using JavaMail?
Try this:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// 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();
}
}
}

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;

This is the code I am using to send an email:
#Override
public void sendEmail(String from, String to, String subject, String content) {
//we set the credentials
final String username = ConfigService.mailUserName;
final String password = ConfigService.mailPassword;
//we set the email properties
Properties props = new Properties();
props.put("mail.smtp.host", ConfigService.mailHost);
props.put("mail.smtp.socketFactory.port", ConfigService.mailSmtpSocketPort);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", ConfigService.mailSmtpPort);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(content);
Transport.send(message);
LOG.info(" Email has been sent");
} catch (MessagingException e) {
LOG.error(" Email can not been sent");
e.printStackTrace();
}
}
When I run this I obtain the next error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
I have seen another question related to this one here, but there is no accepted answer on that question. I can ping to smtp.gmail.com and also I can access the gmail account with the credentials.
This is running in my machine.
Any idea what could be the problem?
I have been experiencing this issue when debugging using NetBeans, even executing the actual jar file. Antivirus would block sending email. You should temporarily disable your antivirus during debugging or exclude NetBeans and the actual jar file from being scanned. In my case, I'm using Avast.
See this link on how to Exclude : How to Add File/Website Exception into avast! Antivirus 2014
It works for me.

javax.mail.SendFailedException: Invalid Addresses (While trying to send emal using Rediffmail)

This program attempts to send email by first connecting to smtp.rediffmail.com . There is no compile time error or compile time exception.But as i try to run the following program it generates the following exception.
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 421 Authorization failed: please authenticate by
doing get message first
I can't figure out what the exception is and why i am getting this exception .
Here is the complete program.In this i have tried to make TLS connection with rediffmail server.
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
class rediff {
public static void main(String args[]) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.rediffmail.com");
props.put("mail.stmp.user", "from");
//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "password");
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "from";
String password = "password";
return new PasswordAuthentication("from", "password");
}
});
String to = "me#gmail.com";
String from = "from#rediff.com";
String subject = "Testing...";
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("rediff program working...!");
Transport transport = session.getTransport("smtp");
transport.send(msg);
System.out.println("fine!!");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
Why do i get this exception ?
as per: http://www.techtalkz.com/microsoft-outlook/193842-pop3.html
In your account settings, enable the "Log on to incoming server before
sending mail" on the "Outgoing Server" tab of your account properties. How
to locate these properties and tabs is Outlook version-specific but you
decided that information wasn't important.
The error is specific to the SMTP service you are trying to use from your client. It's not a code problem. Check your rediffmail.com account settings
The problem with the code is this:
Transport transport = session.getTransport("smtp");
transport.send(msg);
the send method is a static method and you are not suppose to access it with an instance of Transport class. it should be - Transport.send(msg);
You're trying to use TLS auth but I don't see any port settings in your code. Usually smtp server uses different ports for TLS/SSL authentication, try setting it via mail.smtp.socketFactory.port. For TLS default value is 587, for SSL - 993 as far as I remember.
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

I'm trying to use javamail in a groovy script to send out an email via gmail. I've looked many places online and have been unable to get it working thus far. The error I'm getting when running my script is:
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 25, isSSL false
Caught: javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25 (javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?))
It appears to be trying to use port 25 even though I've specified that it should use port 587. Does anyone know what could be causing this problem, I've used telnet to connect to the smtp server on port 587, and thunderbird uses port 587 with STARTTLS security and is able to successfully send mail using the smtp server. This tells me that it is not a blocked port or connectivity issue. Here is the code I'm using to try and send the email:
import javax.mail.*
import javax.mail.internet.*
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('email#gmail.com', 'password');
}
}
def d_email = "email#gmail.com",
d_password = "password",
d_host = "smtp.gmail.com",
d_port = "587", //465,587
m_to = "email#gmail.com",
m_subject = "Testing",
m_text = "This is a test."
def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport.send(msg)
Any help would be greatly appreciated. Thanks in advance!
-Bryan
In Java you would do something similar to:
Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.
For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:
import javax.mail.*
import javax.mail.internet.*
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('email#gmail.com', 'test1234');
}
}
def d_email = "email#gmail.com",
d_uname = "email",
d_password = "password",
d_host = "smtp.gmail.com",
d_port = "465", //465,587
m_to = "testepscript#gmail.com",
m_subject = "Testing",
m_text = "Hey, this is the testing email."
def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Maybe useful for anyone else running into this issue: When setting the port on the properties:
props.put("mail.smtp.port", smtpPort);
..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

Categories