Jerry's Blog

Recording what I learned everyday

View on GitHub


9 May 2019

Java Mail----Sending an Email using Java

by Jerry Zhang

#Tip of the Day:



Send an email with my personal Google account

In last blog, I succeed sending an email inside local host. Today, I can send an email with my personal google account.

public class MailUtils {

    public static void sendEmail(String to, String code) throws MessagingException {
        Security.addProvider(new Provider());
        
        // 1. Create a connection to mail server
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.debug", "true");
        properties.put("mail.smtp.port", "465");
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        Session session = Session.getDefaultInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "<your google account user name>", "<your google account password>");
                    }
                });

        session.setDebug(true);

        // 2. Create an email object
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("<your google email address>"));
        String[] recipients = { to };
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        message.setRecipients(Message.RecipientType.TO, addressTo);
        message.setSubject("Activate your account by clicking the link.");
        message.setContent(
                "<h1>Activate your account by clicking the link blow: </h1>" +
                        "<h3><a href='http://localhost:8080/ActiveServlet?code="+code+"'>" +
                        "http://localhost:8080/ActiveServlet?code="+code+"</a></h3>",
                "text/html; charset=UTF-8");

        // 3. Send the activation email
        Transport.send(message);
    }
}

tags: Java - Mail