2010年10月28日 星期四

透過Gmail發信的Java Sample code

import javax.mail.*;
import javax.mail.internet.*;

import java.util.*;

/**
*     TestMail.class
*     這個Code是使用Java Mail的API、以google當作smtp server來發信。Java Mail可以
* 到 http://www.oracle.com/technetwork/java/index-138643.html 這個網址下載
*
* 這個Code是由下列網址下載而來
* http://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail
*
*/
public class TestMail {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        sendMail();
    }
    public static void sendMail(){
        String host = "smtp.gmail.com";
        String from = "id"; /* gmail的ID,只取@前面的部分 */
        String pass = "";
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true"); // added this line
        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");

        String[] to = {"ywdeng@tw.ibm.com"}; // added this line

        Session session = Session.getDefaultInstance(props, null);
        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++ ) { // changed from a while loop
                    toAddress[i] = new InternetAddress(to[i]);
                }
                System.out.println(Message.RecipientType.TO);

                for( int i=0; i < toAddress.length; i++) { // changed from a while loop
                    message.addRecipient(Message.RecipientType.TO, toAddress[i]);
                }
                message.setSubject("sending in a group");
                message.setText("Welcome to JavaMail");
                Transport transport = session.getTransport("smtp");
                transport.connect(host, from, pass);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}