Send email java

Send email java

Below demo program will show you how to send email to GMAIL account using java program. Please have java program below:

package com.javahonk;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailJava {
    public static void main(String[] args) {

    sendEmailToGmailAccount();

    }

    private static void sendEmailToGmailAccount() {

    try {

        final String username = "username";
        final String password = "password";
        
        //Create distribution list for multiple list separate
        //it by comma(,) example: abc@test.com,def@test.com
        InternetAddress[] distributionList = InternetAddress
            .parse("send@gmail.com,send@gmail.com",
                false);
        //Create CC list for multiple people separate it by comma(,)
        //example: abc@test.com,def@test.com
        InternetAddress[] distributionList_CC = InternetAddress.
            parse("", false);
        String from = "send@gmail.com";
        String subject = "Java Honk test email";

        boolean sessionDebug = false;
        Properties props = new Properties();
        props.put("mail.smtp.port", "587");
        props.put("mail.host", "smtp.gmail.com");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, 
            new javax.mail.Authenticator() {
        protected PasswordAuthentication 
        getPasswordAuthentication() {
            return new PasswordAuthentication(
                username, password);
        }
        });

        session.setDebug(sessionDebug);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, 
            distributionList);
        msg.setRecipients(Message.RecipientType.CC, 
            distributionList_CC);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setText("Email sent sucessfully.");
        Transport.send(msg);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    }
}

 

Output:

Send email java

One thought on “Send email java

Leave a Reply

Your email address will not be published. Required fields are marked *