Posted on

Send an email in Java

Send an email - Java:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

 * This class send an email with javadoc
 * @author Juan Carlos Arcila Diaz
 * @version 1.0
 * @since 23/03/2015
public class SendEmail {

     * This method send an email with javadoc
     * @param toEmail String with the email to send the message
     * @param subject String with the subject of the message
     * @param message String with the message to send
    public void sendEmail(String toEmail, String subject, String message) {

        final String username = "[email protected]"; //change accordingly
        final String password = "password"; //change accordingly

        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");

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

        try {

            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("[email protected]")); //change accordingly
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); //change accordingly



        } catch (MessagingException e) {
            throw new RuntimeException(e);


     * One Example
    public static void main(String[] args) {

        SendEmail sendEmail = new SendEmail();

        sendEmail.sendEmail("[email protected]", "Test", "Test Message");

Enter fullscreen mode Exit fullscreen mode

Top comments (0)