NotOnlyJava

http://www.ibm.com/developerworks/cn/java/j-lo-serial/
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

完整的android use SSL发送邮件

Posted on 2013-09-23 22:48  NotOnlyJava  阅读(584)  评论(0编辑  收藏  举报
package internet.email;

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
 * 邮件发送工具类
 * @author Administrator
 *
 */
public class MailSender extends Authenticator {
    private String user;
    private String password;

    private String[] to;
    private String from;

    private String port;
    private String sport;

    private String host;

    private String subject;
    private String body;

    private boolean auth;
    private boolean debuggable;

    private Multipart multi;

    public MailSender() {
        host = "smtp.qq.com";
        port = "465";
        sport = "465";

        user = "";
        password = "";
        from = "";
        subject = "";
        body = "";

        debuggable = true;
        auth = true;

        multi = new MimeMultipart();

        MailcapCommandMap mc = (MailcapCommandMap) CommandMap
                .getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        CommandMap.setDefaultCommandMap(mc);
    }

    public MailSender(String user, String password) {
        this();
        this.user = user;
        this.password = password;
    }

    public boolean send() throws Exception {
        Properties props = setProperties();

        try {
            Session session = Session.getInstance(props, this);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);

            msg.setFrom(new InternetAddress(from));

            InternetAddress[] addressTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                addressTo[i] = new InternetAddress(to[i]);
            }

            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
            msg.setSubject(subject);
            msg.setSentDate(new Date());

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            multi.addBodyPart(messageBodyPart);

            msg.setContent(multi);

            Transport transport = session.getTransport("smtp");
            transport.connect(host, 25, user, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);

        multi.addBodyPart(messageBodyPart);
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    private Properties setProperties() {
        Properties props = new Properties();

        props.put("mail.smtp.host", host);

        if (debuggable) {
            props.put("mail.debug", "true");
        }

        if (auth) {
            props.put("mail.smtp.auth", "true");
        }

        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.trust", "*");

        props.put("mail.smtp.port", port);
        props.put("mail.smtp.socketFactory.port", sport);
        props.setProperty("mail.smtp.ssl.enable", "true");
        props.setProperty("mail.smtp.ssl.socketFactory.class",
                "DummySSLSocketFactory");
        props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");

        props.put("mail.smtp.starttls.enable", "false");

        return props;
    }

    public void setTo(String[] toAddress) {
        this.to = toAddress;
    }

    public void setFrom(String fromAddress) {
        this.from = fromAddress;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

//----------
package internet.email;

import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

/**
 * 虚拟信任管理器
 * 
 * @author Administrator
 *
 */
public class DummyTrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] cert, String authType) {
        // everything is trusted
    }

    public void checkServerTrusted(X509Certificate[] cert, String authType) {
        // everything is trusted
    }

    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}
//
package internet.email;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
/**
 * SSL工厂
 * @author Administrator
 *
 */
public class DummySSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory factory;

    public DummySSLSocketFactory() {
    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null,
                 new TrustManager[] { new DummyTrustManager()},
                 null);
        factory = (SSLSocketFactory)sslcontext.getSocketFactory();
    } catch(Exception ex) {
        // ignore
    }
    }

    public static SocketFactory getDefault() {
    return new DummySSLSocketFactory();
    }

    public Socket createSocket() throws IOException {
    return factory.createSocket();
    }

    public Socket createSocket(Socket socket, String s, int i, boolean flag)
                throws IOException {
    return factory.createSocket(socket, s, i, flag);
    }

    public Socket createSocket(InetAddress inaddr, int i,
                InetAddress inaddr1, int j) throws IOException {
    return factory.createSocket(inaddr, i, inaddr1, j);
    }

    public Socket createSocket(InetAddress inaddr, int i)
                throws IOException {
    return factory.createSocket(inaddr, i);
    }

    public Socket createSocket(String s, int i, InetAddress inaddr, int j)
                throws IOException {
    return factory.createSocket(s, i, inaddr, j);
    }

    public Socket createSocket(String s, int i) throws IOException {
    return factory.createSocket(s, i);
    }

    public String[] getDefaultCipherSuites() {
    return factory.getDefaultCipherSuites();
    }

    public String[] getSupportedCipherSuites() {
    return factory.getSupportedCipherSuites();
    }
}

 

详见:

Use JavaMail API to send mail  using SSL