使用Jmail发送SSL邮件

来源:互联网 发布:centos终端下载命令 编辑:程序博客网 时间:2024/06/07 02:19

package org.dreams.mail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.sun.mail.smtp.SMTPAddressFailedException;
import com.sun.mail.smtp.SMTPAddressSucceededException;
import com.sun.mail.smtp.SMTPSendFailedException;
import com.sun.mail.smtp.SMTPTransport;

public class JmailSSLSender {

    public static void main(String[] argv) {
        System.setProperty("javax.net.ssl.trustStore", "c://javalib//ssl//mail");//密钥存放的位置
        System.setProperty("javax.net.ssl.trustStorePassword", "打开密钥文件的密码");

        String to = "收信者地址";
        String subject = "hello";//邮件标题
        String from = "送信者地址";
        String cc = "抄送者地址";
        String bcc = null;
        String url = null;

        String mailhost = "smtp.XXX.com";//邮件服务器地址
        String mailer = "JmailSSLSender";
        String file = null;
        String protocol = null;
        String host = "smtp.XXX.com";
        String user = "用户名";
        String password = "密码";

        String record = null; // name of folder in which to record mail
        boolean debug = true;
        boolean verbose = true;
        boolean auth = true;
        boolean ssl = true;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int optind;

        try {

            Properties props = System.getProperties();
            if (mailhost != null)
                props.put("mail.smtp.host", mailhost);

            if (auth) {
                if (ssl) {
                    props.put("mail.smtps.auth", "true");//SSL连接使用的属性
                } else {
                    props.put("mail.smtp.auth", "true");//普通连接的属性
                }

            }

            // Get a Session object
            Session session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("用户名", "密码");
                }
            });

            if (debug) {
                session.setDebug(true);
            }

            // construct the message
            Message msg = new MimeMessage(session);
            if (from != null)
                msg.setFrom(new InternetAddress(from));
            else
                msg.setFrom();

            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            if (cc != null)
                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
            if (bcc != null)
                msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

            msg.setSubject(subject);

            String text = "i am liu!";//collect(in);

            if (file != null) {
                // Attach the specified file.
                // We need a multipart message to hold the attachment.
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(text);
                MimeBodyPart mbp2 = new MimeBodyPart();
                mbp2.attachFile(file);
                MimeMultipart mp = new MimeMultipart();
                mp.addBodyPart(mbp1);
                mp.addBodyPart(mbp2);
                msg.setContent(mp);
            } else {
                // If the desired charset is known, you can use
                // setText(text, charset)
                msg.setText(text);
            }

            msg.setHeader("X-Mailer", mailer);
            msg.setSentDate(new Date());

            // send the thing off
            /*
             * The simple way to send a message is this:
             *
             Transport.send(msg);
             *
             * But we're going to use some SMTP-specific features for
             * demonstration purposes so we need to manage the Transport
             * object explicitly.
             */
            SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
            try {
                if (auth)
                    t.connect(mailhost, user, password);
                else
                    t.connect();

                t.sendMessage(msg, msg.getAllRecipients());
            } finally {
                if (verbose)
                    System.out.println("Response: " + t.getLastServerResponse());
                t.close();
            }

            System.out.println("/nMail was sent successfully.");

            // Keep a copy, if requested.

            if (record != null) {
                // Get a Store object
                Store store = null;
                if (url != null) {
                    URLName urln = new URLName(url);
                    store = session.getStore(urln);
                    store.connect();
                } else {
                    if (protocol != null)
                        store = session.getStore(protocol);
                    else
                        store = session.getStore();

                    // Connect
                    if (host != null || user != null || password != null)
                        store.connect(host, user, password);
                    else
                        store.connect();
                }

                // Get record Folder.  Create if it does not exist.
                Folder folder = store.getFolder(record);
                if (folder == null) {
                    System.err.println("Can't get record folder.");
                    System.exit(1);
                }
                if (!folder.exists())
                    folder.create(Folder.HOLDS_MESSAGES);

                Message[] msgs = new Message[1];
                msgs[0] = msg;
                folder.appendMessages(msgs);

                System.out.println("Mail was recorded successfully.");
            }

        } catch (Exception e) {
            if (e instanceof SendFailedException) {
                MessagingException sfe = (MessagingException) e;
                if (sfe instanceof SMTPSendFailedException) {
                    SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
                    System.out.println("SMTP SEND FAILED:");
                    if (verbose)
                        System.out.println(ssfe.toString());
                    System.out.println("  Command: " + ssfe.getCommand());
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
                    System.out.println("  Response: " + ssfe.getMessage());
                } else {
                    if (verbose)
                        System.out.println("Send failed: " + sfe.toString());
                }
                Exception ne;
                while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
                    sfe = (MessagingException) ne;
                    if (sfe instanceof SMTPAddressFailedException) {
                        SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
                        System.out.println("ADDRESS FAILED:");
                        if (verbose)
                            System.out.println(ssfe.toString());
                        System.out.println("  Address: " + ssfe.getAddress());
                        System.out.println("  Command: " + ssfe.getCommand());
                        System.out.println("  RetCode: " + ssfe.getReturnCode());
                        System.out.println("  Response: " + ssfe.getMessage());
                    } else if (sfe instanceof SMTPAddressSucceededException) {
                        System.out.println("ADDRESS SUCCEEDED:");
                        SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
                        if (verbose)
                            System.out.println(ssfe.toString());
                        System.out.println("  Address: " + ssfe.getAddress());
                        System.out.println("  Command: " + ssfe.getCommand());
                        System.out.println("  RetCode: " + ssfe.getReturnCode());
                        System.out.println("  Response: " + ssfe.getMessage());
                    }
                }
            } else {
                System.out.println("Got Exception: " + e);
                if (verbose)
                    e.printStackTrace();
            }
        }
    }

    public static String collect(BufferedReader in) throws IOException {
        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = in.readLine()) != null) {
            sb.append(line);
            sb.append("/n");
        }
        return sb.toString();
    }
}


 http://blog.csdn.net/kknd97/archive/2006/10/19/1340350.aspx