Java Mail API 學習筆記

 

有很多應用都支持郵件的發送功能,比如ant。

使用普通的java application 發送郵件,需要java mail 庫http://java.sun.com/products/javamail/

和jaf庫http://java.sun.com/products/javamail/

基本代碼如下:

mport java.io.IOException;

import java.io.InputStream;

import java.util.Date;

import java.util.Properties;

import javax.mail.Address;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.SendFailedException;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

/**

 * use Java Mail API to send mails read configuration from mail.properties

 *

 * @author yiqian

 *

 */

public class MailSender {

    private final static String propertiesFileName = "mail.properties";

    /**

     * send the mail

     *

     * @param subject

     *            subject of the mail

     * @param msgText

     *            content of the mail

     */

    public static void send(String subject, String msgText) {

        Properties props = loadProps();

        Session session = Session.getInstance(props, null);

        session.setDebug(false);

        try {

            // create a message

            Message msg = new MimeMessage(session);

            String mailList = props.getProperty("mail.to").trim();

            // create to list

            InternetAddress[] address = InternetAddress.parse(mailList);

            msg.setRecipients(Message.RecipientType.TO, address);

            msg.setSubject(subject);

            msg.setSentDate(new Date());

            // If the desired charset is known, you can use

            // setText(text, charset)

            msg.setText(msgText);

            Transport transport = session.getTransport("smtp");

            transport

                    .connect(props.getProperty("mail.smtp.host"), props

                            .getProperty("mail.user"), props

                            .getProperty("mail.passwd"));

            transport.sendMessage(msg, msg

                    .getRecipients(Message.RecipientType.TO));

        } catch (MessagingException mex) {

            System.out.println("/n--Exception handling in msgsendsample.java");

            mex.printStackTrace();

            System.out.println();

            Exception ex = mex;

            do {

                if (ex instanceof SendFailedException) {

                    SendFailedException sfex = (SendFailedException) ex;

                    Address[] invalid = sfex.getInvalidAddresses();

                    if (invalid != null) {

                        System.out.println("    ** Invalid Addresses");

                        if (invalid != null) {

                            for (int i = 0; i < invalid.length; i++)

                                System.out.println("         " + invalid[i]);

                        }

                    }

                    Address[] validUnsent = sfex.getValidUnsentAddresses();

                    if (validUnsent != null) {

                        System.out.println("    ** ValidUnsent Addresses");

                        if (validUnsent != null) {

                            for (int i = 0; i < validUnsent.length; i++)

                                System.out

                                        .println("         " + validUnsent[i]);

                        }

                    }

                    Address[] validSent = sfex.getValidSentAddresses();

                    if (validSent != null) {

                        System.out.println("    ** ValidSent Addresses");

                        if (validSent != null) {

                            for (int i = 0; i < validSent.length; i++)

                                System.out.println("         " + validSent[i]);

                        }

                    }

                }

                System.out.println();

                if (ex instanceof MessagingException)

                    ex = ((MessagingException) ex).getNextException();

                else

                    ex = null;

            } while (ex != null);

        }

    }

    private static Properties loadProps() {

        Properties props = new Properties();

        InputStream in = null;

        try {

            in = MailSender.class.getResourceAsStream(propertiesFileName);

            props.load(in);

            props.load(in);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                in.close();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

        return props;

    }

    /**

     * @param args

     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        MailSender.send("test subject hot", "hello");

    }

}

其配置文件mail.properties 如下

#SMTP server

mail.smtp.host=

#the user used to connect to SMTP server

mail.user=

mail.passwd=

mail.from=

mail.to=

另可參見http://www.builder.com.cn/2005/1221/224037.shtml

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章