How can I send an email by Java application using GMail, Yahoo, or Hotmail? How can I send an email by Java application using GMail, Yahoo, or Hotmail? java java

How can I send an email by Java application using GMail, Yahoo, or Hotmail?


First download the JavaMail API and make sure the relevant jar files are in your classpath.

Here's a full working example using GMail.

import java.util.*;import javax.mail.*;import javax.mail.internet.*;public class Main {    private static String USER_NAME = "*****";  // GMail user name (just the part before "@gmail.com")    private static String PASSWORD = "********"; // GMail password    private static String RECIPIENT = "lizard.bill@myschool.edu";    public static void main(String[] args) {        String from = USER_NAME;        String pass = PASSWORD;        String[] to = { RECIPIENT }; // list of recipient email addresses        String subject = "Java send mail example";        String body = "Welcome to JavaMail!";        sendFromGMail(from, pass, to, subject, body);    }    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {        Properties props = System.getProperties();        String host = "smtp.gmail.com";        props.put("mail.smtp.starttls.enable", "true");        props.put("mail.smtp.host", host);        props.put("mail.smtp.user", from);        props.put("mail.smtp.password", pass);        props.put("mail.smtp.port", "587");        props.put("mail.smtp.auth", "true");        Session session = Session.getDefaultInstance(props);        MimeMessage message = new MimeMessage(session);        try {            message.setFrom(new InternetAddress(from));            InternetAddress[] toAddress = new InternetAddress[to.length];            // To get the array of addresses            for( int i = 0; i < to.length; i++ ) {                toAddress[i] = new InternetAddress(to[i]);            }            for( int i = 0; i < toAddress.length; i++) {                message.addRecipient(Message.RecipientType.TO, toAddress[i]);            }            message.setSubject(subject);            message.setText(body);            Transport transport = session.getTransport("smtp");            transport.connect(host, from, pass);            transport.sendMessage(message, message.getAllRecipients());            transport.close();        }        catch (AddressException ae) {            ae.printStackTrace();        }        catch (MessagingException me) {            me.printStackTrace();        }    }}

Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)


Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.


Something like this (sounds like you just need to change your SMTP server):

String host = "smtp.gmail.com";String from = "user name";Properties props = System.getProperties();props.put("mail.smtp.host", host);props.put("mail.smtp.user", from);props.put("mail.smtp.password", "asdfgh");props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mailprops.put("mail.smtp.auth", "true");Session session = Session.getDefaultInstance(props, null);MimeMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(from));InternetAddress[] to_address = new InternetAddress[to.length];int i = 0;// To get the array of addresseswhile (to[i] != null) {    to_address[i] = new InternetAddress(to[i]);    i++;}System.out.println(Message.RecipientType.TO);i = 0;while (to_address[i] != null) {    message.addRecipient(Message.RecipientType.TO, to_address[i]);    i++;}message.setSubject("sending in a group");message.setText("Welcome to JavaMail");// alternately, to send HTML mail:// message.setContent("<p>Welcome to JavaMail</p>", "text/html");Transport transport = session.getTransport("smtp");transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");transport.sendMessage(message, message.getAllRecipients());transport.close();


Other people have good answers above, but I wanted to add a note on my experience here. I've found that when using Gmail as an outbound SMTP server for my webapp, Gmail only lets me send ~10 or so messages before responding with an anti-spam response that I have to manually step through to re-enable SMTP access. The emails I was sending were not spam, but were website "welcome" emails when users registered with my system. So, YMMV, and I wouldn't rely on Gmail for a production webapp. If you're sending email on a user's behalf, like an installed desktop app (where the user enters their own Gmail credentials), you may be okay.

Also, if you're using Spring, here's a working config to use Gmail for outbound SMTP:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">    <property name="defaultEncoding" value="UTF-8"/>    <property name="host" value="smtp.gmail.com"/>    <property name="port" value="465"/>    <property name="username" value="${mail.username}"/>    <property name="password" value="${mail.password}"/>    <property name="javaMailProperties">        <value>            mail.debug=true            mail.smtp.auth=true            mail.smtp.socketFactory.class=java.net.SocketFactory            mail.smtp.socketFactory.fallback=false        </value>    </property></bean>