Saturday 24 March 2018

Code Snippet to Send Email Notification using Java Transport API.

public static void main(String[] args){
        final String username = "<SMTP Server User Name>";
        final String password = "<SMTP Server Password>";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "<SMTP Server Host Name>");
        props.put("mail.smtp.port", "<SMTP Server Port>"); //generally it is 25.

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                }
          });

        try{
            Message message = new MimeMessage(session);
           
            //set from email address
            message.setFrom(new InternetAddress("anandrajbadal@gmail.com"));
           
            //set TO Recipients
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("anandrajbadal@ymail.com"));
           
            //set CC Recipients
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("anandrajbadal@rediff.com"));
           
            //set subject
            message.setSubject("Test Mail");
           
            //set body
            message.setText("This is test email");
   
            Transport.send(message);
            System.out.println("Email sent successfully");
        }catch(MessagingException e){
            throw new RuntimeException(e);
        }
 }


Happy Learning!!!

No comments:

Post a Comment