Error sending email with JavaMail - java

The following code works only when Google's "Allow less secure apps" is ON, if that feature is off I get javax.mail.AuthenticationFailedException, how do I get it to work when that feature is OFF?
public static void main(String[] args) {
String username = "USER-NAME#gmail.com";
String password = "PASSWORD";
String to = "USER-NAME#msn.com";
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.list(System.out);
Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("This is the subject line!");
msg.setText("This is the actual message");
System.out.println("Sending message...");
Transport.send(msg, username, password);
System.out.println("Message sent!");
} catch (MessagingException ex) {
Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}

Related

How to send java mail in spring mvc

I have an web application in which i am sending mail to user. Following is my code.
String host = "smtp.gmail.com";
String pwd = "123";
String from = "sender#gmail.com";
String to = "receiver#gmail.com";
String subject = "Test";
String messageText = "This is demo mail";
int port = 587;
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] add = {new InternetAddress(to)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, add);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText); //Actual msg
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, from, pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
This code is executed on local but fails on server domain. I have search a lot but that solution didn't work for me.
I tried a lot like replacing transport.connect(host, from, pwd); with transport.connect(host, 587, from, pwd); or 465and also String host="smtp.gmail.com"; with static domain IP. but still not working.
can anyone figure out what i am missing..?
Here is working example.
If this didn't work then there must be a problem with your server..
public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
try {
logger.info("Sending Email to : " + recipient + " Subject :" + subject);
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName, userName));
if (recipient.contains(";")) {
String[] recipientList = recipient.split(";");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String obj: recipientList) {
recipientAddress[counter] = new InternetAddress(obj.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
} else {
InternetAddress[] recipientAddress = {
new InternetAddress(recipient)
};
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFile != null) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(attachFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
} catch (Exception e) {
logger.error("ERROR In Sending Email :" + e, e);
}
}

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.

sending mail using java from pc to mobile

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/

Reviecing email from zoho mail server

iam trying to read emails from company specific generated email server, this is my code and i am not able to establish connection with server since it's a linux server.
public class Testing {
public static void main(String[] args) {
String from = "email";
String pass = "pwd";
String to = "toId";
String host = "pop.zoho.com";
String port = "995";
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "995");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Please do the need full help
thanks in advance

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

Categories