Month: February 2019

  • Send email from Java application using Java Mail API

    Send email from Java application using Java Mail API

    Java Mail API allows to send emails from your Java application. Very often it will be necessary to send emails when you are developing a business related applications or simply hobby projects.

    Using Java Mail API is relatively straightforward. First you need to add the API to your application. You can download the JAR file from https://javaee.github.io/javamail/

    You need following data fields to send email

    • An account to send email from.
    • Password of your email account.
    • SMTP server host address
    • SMTP server port.

    In the following example, we will use gmail account for sending email. For google, SMTP server host address is “smtp.gmail.com” and port is “587”.

    Enable Less Secure Access in Gmail

    Google recently updated their security by automatically disabling access from third-party application. So you have to enable less secure access from gmail settings in order to use that account from java application.

    You can enable it from https://myaccount.google.com/security

    If you haven’t enabled it, you will get following email when you try to send email.

    Sign-in attempt was blocked.
    Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access.


    Enable less secure app access from Google settings

    Program for sending email using Java Mail API and Gmail account

        public static void sendMail(String recepient) throws Exception {
            System.out.println("Preparing to send email");
            Properties properties = new Properties();
    
            //Enable authentication
            properties.put("mail.smtp.auth", "true");
            //Set TLS encryption enabled
            properties.put("mail.smtp.starttls.enable", "true");
            //Set SMTP host
            properties.put("mail.smtp.host", "smtp.gmail.com");
            //Set smtp port
            properties.put("mail.smtp.port", "587");
    
            //Your gmail address
            String myAccountEmail = "[email protected]";
            //Your gmail password
            String password = "xxxxxxxx";
    
            //Create a session with account credentials
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(myAccountEmail, password);
                }
            });
    
            //Prepare email message
            Message message = prepareMessage(session, myAccountEmail, recepient);
    
            //Send mail
            Transport.send(message);
            System.out.println("Message sent successfully");
        }
    
        private static Message prepareMessage(Session session, String myAccountEmail, String recepient) {
            try {
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(myAccountEmail));
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
                message.setSubject("My First Email from Java App");
                String htmlCode = "<h1> WE LOVE JAVA </h1> <br/> <h2><b>Next Line </b></h2>";
                message.setContent(htmlCode, "text/html");
                return message;
            } catch (Exception ex) {
                Logger.getLogger(JavaMailUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }