I\'m not familiar with this function to send mail in java. I\'m getting an error while sending email to reset a password. Hope you can give me a solution.
Below is m
2 possible reasons:
There are a few steps you have to keep in mind.
Now there are two scenarios If you are developing it in your local machine login to your google account in your browser, this way the google recognizes the machine.
If you have deployed the application onto a server then after the first request you will get an authentication error, so you have to give access to the server, just go here to give access- https://www.google.com/accounts/DisplayUnlockCaptcha
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail1 {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "valid email to address";
// Sender's email ID needs to be mentioned
String from = "valid email from address";
// Get system properties
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator () {
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("userid","password");//userid and password for "from" email address
}
};
Session session = Session.getDefaultInstance( properties , authenticator);
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();
}
}
}