I am currently ready to write a simple program to send email through gmail to a gmail account. I tried various methods, but often I end up with the same error: "Could not connect to the SMTP host: smtp.gmail.com, port: 587;"
Does it have anything to do with property settings. Here is a snippet from my program. Finding a solution :)
Thank you in advance
public static boolean SendMail(String from, String password, String message, String to[]){
String host = "smtp.gmail.com";
Properties prop = System.getProperties();
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.user", from);
prop.put("mail.smtp.password", password);
prop.put("mail.smtp.port", 587);
prop.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(prop, null);
MimeMessage mimemsg = new MimeMessage(session);
try{
mimemsg.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i=0;i<to.length;i++){
toAddress[i] = new InternetAddress(to[i]);
}
for(int j=0;j<toAddress.length;j++){
mimemsg.addRecipient(RecipientType.TO, toAddress[j]);
}
mimemsg.setSubject(" MAIL from JAVA Program");
mimemsg.setText(message);
Transport trans = session.getTransport("smtp");
trans.connect(host,from,password);
trans.sendMessage(mimemsg, mimemsg.getAllRecipients());
trans.close();
return true;
}catch(MessagingException me){
me.printStackTrace();
}
return false;
}
source
share