/*
 *Source File Name:   SMTPClient.java
 *@author : [email protected]
 */
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.event.*;
import javax.activation.*;
public class SMTPClient implements ConnectionListener, TransportListener {
private InternetAddress hostname;
private String host;
private String from;
private InternetAddress fromAddress;
private InternetAddress receiveAddress[];
private InternetAddress replyTos[];
private String receive[];
private String auth;
private String ehlo;
private String username;
private String password;
private String subject;
private String content;
private String contentType;
private String charset;
    private MimeBodyPart mimeParts[];
    private String attachmentFiles[];
    private String reply[];
    private Date sendDate;
    private boolean debugFlag;    public SMTPClient() {
        from = "";
        receive = new String[0];
        host = "localhost";
        subject = "test";
        content = "";
        contentType = "text/plain";
        charset = "gb2312";
        mimeParts = new MimeBodyPart[0];
        attachmentFiles = new String[0];
        reply = new String[0];
        sendDate = new Date();
        debugFlag = false;
        auth = "false";
        ehlo = "false";
    }    public void setFromAddress(String fromAddr) {
        from = fromAddr;
    }
    public void setFromAddress(InternetAddress fromAddr) {
        fromAddress = fromAddr;
        from = null;
    }    public String getFromAddress() {
        return from;
    }

    public void setToAddresses(String toAddress[]) {
        receive = toAddress;
    }    public void setToAddress(String toAddress) {
        receive = (new String[] {toAddress} );
    }    public void setToAddresses(InternetAddress to[]) {
        receiveAddress = to;
        receive = null;
    }    public String[] getToAddresses() {
        return receive;
    }
    
    public void setHost(String h) {
        host = h;
    } public void setHost(InternetAddress h) {
hostname = h;
}

    public String getHost() {
        return host;
    }
    
    public void setSubject(String subj) {
        subject = subj;
    }    public String getSubject() {
        return subject;
    }    public void setReplyToAddresses(String replyTo[]) {
        reply = replyTo;
    }    public void setReplyToAddresses(InternetAddress replyTo[]) {
        replyTos = replyTo;
        reply = null;
    }    public void setReplyToAddress(String replyTo) {
        reply = (new String[] {replyTo});
    }    public String[] getReplyToAddresses() {
        return reply;
    }
    
    public void setTextContent(String cont) {
        content = cont;
    }    public String getTextContent() {
        return content;
    }    public void setContentType(String contType) {
        contentType = contType;
    }    public String getContentType() {
        return contentType;
    }    public void setCharset(String encoding) {
        charset = encoding;
    }    public String getCharset() {
        return charset;
    } public void enableAUTH() {
auth = "true";
ehlo = "true";
}

public void disableAUTH() {
auth = "false";
ehlo = "false";
}

    public void setMimeParts(MimeBodyPart mimeParts[]) {
        mimeParts = mimeParts;
        attachmentFiles = null;
    }    public MimeBodyPart[] getMimeParts() {
        return mimeParts;
    }    public void setFileAttachments(String files[]) {
        attachmentFiles = files;
    }    public void setFileAttachment(String filename) {
        attachmentFiles = (new String[] {
            filename
        });
        mimeParts = null;
    }    public String[] getFileAttachments() {
        return attachmentFiles;
    }    public void setDebug(boolean debug) {
        debugFlag = debug;
    }    public boolean getDebug() {
        return debugFlag;
    }    public void setSentDate(Date sentDate) {
        sendDate = sentDate;
    }    public Date getSentDate() {
        return sendDate;
    }    public void setUserName(String name) {
        username = name;
    }    public String getUserName() {
        return username;
    }    public void setPassword(String passwd) {
        password = passwd;
    }    public String getPassword() {
        return password;
    }    public boolean isOK() {
        return host != null && receiveAddress != null && fromAddress != null;
    }

解决方案 »

  1.   

    public void sendMessage() {
         Transport trans = null;
         try {
            if(receiveAddress == null) {
             int toCount = receive.length;
                receiveAddress = new InternetAddress[toCount];
                for(int i = 0; i < toCount; i++) {
                    receiveAddress[i] = new InternetAddress(receive[i]);
                }
            }
            if(fromAddress == null)
                fromAddress = new InternetAddress(from);         Properties props = new Properties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.ehlo", ehlo);
        props.put("mail.smtp.auth", auth);
         System.out.println("in try");         Session session = Session.getDefaultInstance(props, null);         session.setDebug(debugFlag);

            MimeMessage msg = new MimeMessage(session);         msg.setFrom(fromAddress);
            msg.setRecipients(javax.mail.Message.RecipientType.TO, receiveAddress);         if(subject != null && !subject.equals(""))
                msg.setSubject(subject, charset);         if(replyTos != null || reply != null) {
                if(reply != null) {
                    replyTos = new InternetAddress[reply.length];
                    for(int i = 0; i < reply.length; i++) {
                        replyTos[i] = new InternetAddress(reply[i]);
                    }
                }
                msg.setReplyTo(replyTos);
            }         msg.setSentDate(sendDate);
            if(mimeParts != null && mimeParts.length != 0) {
                Multipart mpart = new MimeMultipart();
                if(content != null && !content.equals("")) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    mbp.setContent(content, contentType);
                    mpart.addBodyPart(mbp);
                }
                for(int i = 0; i < mimeParts.length; i++)
                    mpart.addBodyPart(mimeParts[i]);

                msg.setContent(mpart);
            } else if(attachmentFiles != null && attachmentFiles.length != 0) {
                Multipart mpart = new MimeMultipart();
                if(content != null && !content.equals("")) {
                    MimeBodyPart mb = new MimeBodyPart();
                    ////mb.setContent(content, contentType);
                    mb.setText(content, charset);
                    mpart.addBodyPart(mb);
                }
                for(int i = 0; i < attachmentFiles.length; i++) {
                    MimeBodyPart mb = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(attachmentFiles[i]);
                    mb.setDataHandler(new DataHandler(fds));
                    mb.setFileName((new File(attachmentFiles[i])).getName());
                    mpart.addBodyPart(mb);
                }

                msg.setContent(mpart);
            } else if(content != null && !content.equals(""))
                msg.setContent(content, contentType);
                
            
            msg.saveChanges();
            trans = session.getTransport(receiveAddress[0]);
            // register ourselves as listener for ConnectionEvents 
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);
            
            if(username != null && password != null) {
    trans.connect(host, username, password);
    msg.saveChanges();
            } else {
             trans.connect();
            }
            //msg.saveChanges();
            trans.sendMessage(msg, receiveAddress);
                // give the EventQueue enough time to fire its events
        try {Thread.sleep(5);}catch(InterruptedException e) {}
    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {Thread.sleep(5);}catch(InterruptedException e) {}

        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);
    } finally {
        try {
    // close the transport
    trans.close();
        } catch (MessagingException mex) { /* ignore */ }
    }
        }    // implement ConnectionListener interface
        public void opened(ConnectionEvent e) {
    System.out.println(">>> ConnectionListener.opened()");
        }
        public void disconnected(ConnectionEvent e) {}
        public void closed(ConnectionEvent e) {
    System.out.println(">>> ConnectionListener.closed()");
        }    // implement TransportListener interface
        public void messageDelivered(TransportEvent e) {
    System.out.print(">>> TransportListener.messageDelivered().");
    System.out.println(" Valid Addresses:");
    Address[] valid = e.getValidSentAddresses();
    if (valid != null) {
         for (int i = 0; i < valid.length; i++) 
    System.out.println("    " + valid[i]);
    }
        }
        
        public void messageNotDelivered(TransportEvent e) {
    System.out.print(">>> TransportListener.messageNotDelivered().");
    System.out.println(" Invalid Addresses:");
    Address[] invalid = e.getInvalidAddresses();
    if (invalid != null) {
        for (int i = 0; i < invalid.length; i++) 
    System.out.println("    " + invalid[i]);
    }
        }
        public void messagePartiallyDelivered(TransportEvent e) {
    // SMTPTransport doesn't partially deliver msgs
        }
        public static void main(String[] args) {
         SMTPClient cl=new SMTPClient();
            cl.setHost("smtp.etang.com");        //cl.setFromAddress("[email protected]");
            cl.setFromAddress("[email protected]");        cl.setToAddresses(new String[]{"[email protected]", "[email protected]"} );        cl.setReplyToAddresses( new String[]{"[email protected]"} );
            cl.enableAUTH();
            cl.setUserName("youname");
            cl.setPassword("youpassword");
            cl.setCharset("gb2312");        cl.setSubject("&sup2;&acirc;&Ecirc;&Ocirc;");
            cl.setFileAttachments(new String[]{"attachment1.txt", "k.jqs"});
            cl.setTextContent("&Auml;&atilde;&ordm;&Atilde;");
            //cl.setContentType("text/html"); //for HTML messaging        cl.sendMessage();
        }
    }