Hi,,
You need set object properties. Take a look these code below
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author user
*/
public class SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "userTo@gmail.com";
// Sender's email ID needs to be mentioned
String from = "userFrom@gmail.com";
// Assuming you are sending email from localhost
String host = "gmail.com";
// Get system properties
// Properties properties = System.getProperties();
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.auth", "true");
properties.put("mail.debug", "false");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.port", "465");
// Setup mail server
// properties.setProperty("smtp.gmail.com", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, new Authenticator() {@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("userFrom@gmail.com", "YourPassword");
}});
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();
}
}
}