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);
}
Related
It is showing following error ::
Exception in thread "main" java.lang.RuntimeException:
javax.mail.MessagingException: Could not connect to SMTP host:
localhost, port: 587, response: 421 at
SendMail.main(SendMail.java:54) Caused by:
javax.mail.MessagingException: Could not connect to SMTP host:
localhost, port: 587, response: 421 at
com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2088)
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
javax.mail.Transport.send0(Transport.java:254) at
javax.mail.Transport.send(Transport.java:124) at
SendMail.main(SendMail.java:49) Java Result: 1 BUILD SUCCESSFUL (total
time: 2 seconds)
and my code is:
`public class SendMail {
public static void main(String[] args) throws Exception{
final String smtp_host = "smtp.gmail.com";
final String smtp_username = "xxx#gmail.com";
final String smtp_password = "xxxxxx";
final String smtp_connection = "TLS";
final String toEmail="xxx#gmail.com";
final String fromEmail="yyy#example.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
if (smtp_connection.equals("TLS")) {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
} else{
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
}
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtp_username, smtp_password);
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromEmail, "NoReply"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail, "Mr. Recipient"));
msg.setSubject("Welcome To JavaMail API");
msg.setText("JavaMail API Test - Sending email example through remote smtp server");
Transport.send(msg);
System.out.println("Email sent successfully...");
} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}`
Below is the working code. You are not setting an SSL socket factory in the non-TLS case.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#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 = "hi ....,!";
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";
props.put("mail.smtp.starttls.enable", "true");
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");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
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]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
To connect to google SMTP server, make sure you are using TLS/SSL. It is required.
Go to gmail account Click on the Forwarding/IMAP tab and scroll down to the IMAP Access section: IMAP must be enabled in order for emails to be properly copied to your sent folder.
And Try Change This
if (smtp_connection.equals("TLS")) {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
} else{
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
}
To This
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.user", "username"); // User name
properties.put("mail.smtp.password", "password"); // password
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
I'm trying to configure my app to send mail, using gmail. I looked up the gmail javamail documentation and I've been able to write that piece of code:
String from = mymail;
String pass = mypass;
String[] to = { somemail }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
MimeMessage message = new MimeMessage(session);
try {
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]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
but I keep getting the following error:
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.c....
What should I try to change ?
It may be that Gmail account is not configured to use less secure authentication. You can change that by logging into the account you are trying to send email from and then going to this page. On that page you can turn on access by less secure authentication. This should solve the problem
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.
final String username = "<mail_name>";
final String password = "<password>";
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", "465");
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("<mail_from>#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("<mail_to>#gmail.com"));
message.setSubject("Test Subject");
message.setText("Test");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
I have tried this code for sending mail from pc to mobile but it giving error while compiling . Can any one help me to send mail?
public class sendmail{
public static void mail(String args[]){
final String fromEmail = ""; //requires valid gmail id
final String password = ""; // correct password for gmail id
final String toEmail = "" // can be any email id
System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
String subject = "";//subject here
String body = "";//mail body here
sendEmail(session, toEmail, subject, body);
}
public static void sendEmail(Session session, String toEmail, String subject, String body) {
try {
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no-reply#anyname.com", "any name"));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("ERROR:" + e.getMessage());
}
}
}
What is mean by PC to Mobile. PC & mobile both are hardware devices to access the mail.Please follow the below link for sending mail in java using java mail API via gmail SMTP.
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
I have this servlet which needs to send mail using Java Mail API, however I am getting no password specified error, although the password work with gmail.
MailServiceImpl.java:
public class MailServiceImpl extends RemoteServiceServlet implements MailService {
private static String HOST = "smtp.gmail.com";
private static int PORT = 465;
private String username = "foo#gmail.com";
private String password = "foo123";
private Properties props = new Properties();
#Override
public void sendMail(String email) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("foo#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("foo#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Subcriber Email:," +
"\n\n " + email);
Transport transport = session.getTransport("smtp");
transport.connect(HOST, PORT, username, password);
Transport.send(message);
transport.close(); // -- needed?
} catch (Exception e) {
e.printStackTrace();
}
}
}
However I am getting this error:
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.mygwtapp.server.MailServiceImpl.sendMail(MailServiceImpl.java:43)
Try using SSL connection. It worked for me.
Properties props = new Properties();
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.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#test.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to#test.com"));
message.setSubject("Testing Subject");
message.setText("mail text");
Transport.send(message);
System.out.println("OK");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}