This code allows the user to login to his/her mail account to send a mail to another recepient.First the code needs to be configured by entering the Server details and user credentials .This code authenticates the user and creates a session then a MimeMessage Object is created where the subject and content of the mail is set.
public class SmtpMail{ public static void main(String[] args) { 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"); final String username = "Username@gmail.com"; final String password = "Password"; Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("toEmailAddress@yahoo.com")); System.out.println(session.toString()); message.setSubject("JavaMail Subject"); message.setText("Dear Recepient," + "\n\n This is a Test Mail"); System.out.println(session.toString()); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }