Validate smtp server credentials using java without actually sending mail - java

To verify smtp server credentials shall I use transport.connect()?
Session session = Session.getInstance(properties,authenticator);
Transport tr=session.getTransport("smtp");
tr.connect();
Is it correct method to check smtp server credentials?

This question: 'Verify mail server connection programmatically in ColdFusion' has a java solution as part of the accepted answer:
int port = 587;
String host = "smtp.gmail.com";
String user = "username#gmail.com";
String pwd = "email password";
try {
Properties props = new Properties();
// required for gmail
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
// or use getDefaultInstance instance if desired...
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
transport.connect(host, port, user, pwd);
transport.close();
System.out.println("success");
}
catch(AuthenticationFailedException e) {
System.out.println("AuthenticationFailedException - for authentication failures");
e.printStackTrace();
}
catch(MessagingException e) {
System.out.println("for other failures");
e.printStackTrace();
}

public boolean confirmSMTP(String host, String port, String username, String password, String auth, String enctype) {
boolean result = false;
try {
Properties props = new Properties();
if (auth.equals(true)) {
props.setProperty("mail.smtp.auth", "true");
} else {
props.setProperty("mail.smtp.auth", "false");
}
if (enctype.endsWith("TLS")) {
props.setProperty("mail.smtp.starttls.enable", "true");
} else if (enctype.endsWith("SSL")) {
props.setProperty("mail.smtp.startssl.enable", "true");
}
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
int portint = Integer.parseInt(port);
transport.connect(host, portint, username, password);
transport.close();
result = true;
} catch(AuthenticationFailedException e) {
Logging.addMsg(e.toString(), "SMTP: Authentication Failed", false, true);
} catch(MessagingException e) {
Logging.addMsg(e.toString(), "SMTP: Messaging Exception Occurred", false, true);
} catch (Exception e) {
Logging.addMsg(e.toString(), "SMTP: Unknown Exception", false, true);
}
return result;
}

Related

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Client was not authenticated

I am getting the 'com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Client was not authenticated' error always, can somebody tell me what am I doing wrong in my code?
Properties mailprops = new Properties();
mailprops.setProperty("mail.transport.protocol", "smtp");
mailprops.setProperty("mail.smtp.host", "MyHost");
mailprops.setProperty("mail.smtp.user", "UserName");
mailprops.setProperty("mail.smtp.password", "Password");
Session mailSession = Session.getDefaultInstance(mailprops, null);
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(mySubject);
message.addRecipient(To);
message.addFrom(from address);
try{
Transport.send(message);
}catch (SendFailedException sfe) {
}catch (MessagingException mex) {
}
Try below approach,
Provide the Authenticator object to create the session object
public class MailWithPasswordAuthentication {
public static void main(String[] args) throws MessagingException {
new MailWithPasswordAuthentication().run();
}
private void run() throws MessagingException {
Message message = new MimeMessage(getSession());
message.addRecipient(RecipientType.TO, new InternetAddress("to#example.com"));
message.addFrom(new InternetAddress[] { new InternetAddress("from#example.com") });
message.setSubject("the subject");
message.setContent("the body", "text/plain");
Transport.send(message);
}
private Session getSession() {
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.host", "mail.example.com");
properties.setProperty("mail.smtp.port", "25");
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "auth-user";
String password = "auth-password";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
}
Try something like that:
Transport trans = sess.getTransport("smtp");
try {
String host = sess.getProperty("mail.smtp.host");
String port = sess.getProperty("mail.smtp.port");
String user = sess.getProperty("mail.smtp.user");
String password = sess.getProperty("mail.smtp.password");
int prt = port == null ? -1 : Integer.parseInt(port);
trans.connect(host, prt, user, password);
trans.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
} finally {
trans.close();
}
UPDATE:
Or rather:
int prt = port == null ? 25 : Integer.parseInt(port);
enable authentication.
enable STARTTLS.
create Authenticator object to pass in Session.getInstance argument.
Sample code:
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
You don't need an Authenticator as some answers suggest. There is no mail.smtp.password property. Call the Transport.send method that takes a username and password.

Java Transport mail sender error

I'm need to send an email after persist an object on my JAVA project, I'm using this code
public static void sendMail(String protocol, String host, String port, final String userName, final String password,
String subject, byte[] content, String para, String cc, String co) {
Properties props = getServerProperties(protocol, host, port);
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
final Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(userName));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(para));
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(co));
message.setSubject(subject);
message.setText(content.toString());
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private static Properties getServerProperties(String protocol, String host, String port) {
Properties properties = new Properties();
properties.put(String.format("mail.%s.host", protocol), host);
properties.put(String.format("mail.%s.port", protocol), port);
properties.setProperty(String.format("mail.%s.socketFactory.class", protocol), "javax.net.ssl.SSLSocketFactory");
properties.setProperty(String.format("mail.%s.socketFactory.fallback", protocol), "false");
properties.setProperty(String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port));
return properties;
}
but when I call Transport.send(message); returns me an error message
Can't make API call mail.Send in a thread that is neither the original request thread nor a thread created by ThreadManager
What i'm doing wrong on mailer?

Java Email sending API email did not send.. hang up the program

I was code a java email sending program. But when i click the send button the button appear hanging mode & program still running, but mail did not send.
I can't detect the problem. can anybody help me...
The code is below.
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myid#gmail.com", "password");
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("myid#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("senderid#gmail.com"));
message.setSubject("Demo mail");
message.setText("Hello, world!");
Transport.send(message);
JOptionPane.showMessageDialog(this, "Message sent!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e);
}
My email account have not activate 2-step verification service.
And it also work in outlook email sending software.. I tested.
But not work on my java program.
I believe the Authenticator class should be extended. Here is an example that works for me:
public class SendEmail {
public SendEmail () {}
public void send (String text){
String host = "smtp.gmail.com";
String username = "user#email.com";
String password = "password";
Properties props = new Properties();
// set any needed mail.smtps.* properties here
Session session = Session.getInstance(props, new GMailAuthenticator("user", "password"));
Message msg = new MimeMessage(session);
Transport t;
try {
msg.setText(text);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("stackkinggame#gmail.com", "Stack King"));
t = session.getTransport("smtps");
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
Gdx.app.log("Email", "Message sent successfully.");
}
catch (Exception e) {
e.printStackTrace();
}
}
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
}
First, fix all the common JavaMail mistakes in your program.
Second, since you're using Gmail, make sure you've enabled support for less secure apps.
Finally, you need to provide more details than "it doesn't work". The JavaMail debug output would be helpful.

Cpanel Java Email Client Program

If anyone tried/found working java email/smtp/imap client program that connects to cPanel's email a/cs and send emails out then please share it. It has been a tiresome efforts in trying to find that code online but none of them works fine. I did try more than five varieties of code but nothing worked. Below are few samples:
Sample# 1
String host = "mail.domain.net";
String user = "catch-all#domain.net";
String pass = "xxxx";
String to = "admin#domain.net";
String from = "catch-all#domain.net";
String subject = "Dummy subject";
String messageText = "Dummy body";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", 2525); //25 - default
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
try {
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
Error
Sending mail.. Done!javax.mail.MessagingException: Could not connect to SMTP host: mail.dealstock.net, port: 25;
nested exception is:
java.net.ConnectException: Connection refused
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:291)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:192)
at com.mail.EmailsSender2.main(EmailsSender2.java:209)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mai
From the Cpanel account, the designated port is 2525, if secured then 465, but none of the ports work. With post 2525, it does connects, but there is no response and waits for 1-2 minitues and then timeouts. If I change to port 25, then it simply throws above error. With same Cpanel email a/c my another program able to connect and read emails through POP, but failing with sending emails.
Appreciate if you can share your comments/inputs.
I have hostgator, and when creating session, use the following code it works (with no encryption or SSL, not TLS).
btw, port 25 is blocked by my isp (Verizon), and hostgator has it on port 26, not 2525. make sure your hosting company has it running on 2525.
private Session getSession(final EmailConfig emailConfig) {
String port = Integer.toString(emailConfig.getPort());
Properties props = new Properties();
props.put("mail.smtp.host", emailConfig.getHost());
props.put("mail.smtp.port", port);
if (Encryption.SSL == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
else if (Encryption.TLS == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
}
return Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(), emailConfig.getDecryptedPassword());
}
});
}
private void sendMessage(Session session, InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, String subject, String text) throws AuthenticationFailedException {
Message message = new MimeMessage(session);
try {
message.setFrom(from);
if (to != null) {
message.setRecipients(Message.RecipientType.TO, to);
}
if (cc != null) {
message.setRecipients(Message.RecipientType.CC, cc);
}
if (bcc != null) {
message.setRecipients(Message.RecipientType.BCC, bcc);
}
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
catch (AuthenticationFailedException ex) {
log.info("authentication failed", ex);
throw ex;
}
catch (MessagingException e) {
log.info("error sending message", e);
e.printStackTrace();
}
}
This would definitely work for you.
Just call this function to send automated email to client.
In parameter "to" is email address to which you want to send an email.
I usually do it in Maven project. If you are using maven project then import following dependencies.
https://mvnrepository.com/artifact/javax.mail/mail/1.4
final String username = "youremail#gmail.com";
final String password = "yourpassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
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("youremail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}

How to check whether the email account is valid?

I have already written code to check the email account it is working for gmail & yahoo mail
but it is not working for hotmail & AOL. Below is the code I have used. If any idea please help.
I am getting following exception when I pass hotmail account:
javax.mail.MessagingException: Exception reading response;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Code:
public boolean checkEmailAccountInfo(final String userMailID,
final String password, String outgoingMailServer, String portNo) {
try {
Properties p = new Properties();
// Boolean b = new Boolean(true);
p.put("mail.smtps.auth", true);
p.put("mail.smtp.user", userMailID);
p.put("mail.smtp.host", outgoingMailServer);
p.put("mail.smtp.port", portNo);
p.put("mail.smtp.starttls.enable", true);
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.8BITMIME", "true");
p.put("mail.smtp.PIPELINING", "true");
p.put("mail.smtp.socketFactory.port", 465);
p.put("mail.smtp.debug", "true");
p.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
p.put("mail.smtp.socketFactory.fallback", "false");
// create some properties and get the default Session
javax.mail.Session session = javax.mail.Session.getInstance(p,
new javax.mail.Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userMailID,
password);
}
});
session.setDebug(false);
Transport t = session.getTransport("smtp");
t.connect();
boolean isConnected = t.isConnected();
if (isConnected) {
t.close();
return true;
}
return false;
} catch (Exception e) {
return false;
}
}
You can try for this :
p.put("mail.smtp.socketFactory.port", portNo);
This will work .I have tested it with other mail ids.

Categories