Loading
 
What's Next: View All Tutorial →

Java Program to send email using javax.mail - gmail account

A simple program to send email to the gmail account 1. TestMail.java import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication...

Published Date: 11/01/2015  Last Modified Date: 11/01/2015    New Post



A simple program to send email to the gmail account


1. TestMail.java

import java.util.Properties;
import javax.mail.Authenticator;
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;

/**
 *
 * @author catchmycity
 */
public class TestMail {

    public static String sendEmail(String toEmail, String subject, String body) {

        final String userName = "*****@gmail.com";
        final String passWord = "*****";
        String fromEmail = "*****@gmail.com";
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");
        props.put("mail.debug", "true");

        Session session;
        session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, passWord);
            }
        });

        session.setDebug(false);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(fromEmail));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            message.setSubject(subject);
            message.setText(body);
            Transport.send(message);
            return "success";
        } catch (MessagingException e) {
            System.out.println(e.getMessage());
            return "failure";
        }
    }

    public static void main(String args[]) {
        String mailResult = TestMail.sendEmail("****@gmail.com", "subject", " body content");

    }
}


Dependency Jar 
 
<dependency>
       <groupId>javax.mail</groupId>
       <artifactId>mail</artifactId>
       <version>1.4.7</version>
       <scope>provided</scope>
</dependency>






 
Awaiting for Administrator approval




← Back to list


Related Post




×