javamail

JavaMail

Java 官方提供了对电子邮件协议封装的 Java 类库,就是JavaMail,但并没有包含到标准的 JDK 中,需要我们自己去 Java 或 Oracle 官网下载。


下载地址: 
https://java.net/projects/javamail/pages/Home 
或者 
http://www.oracle.com/technetwork/java/javamail/index.html


自建了一个发送类:

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


import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class Mymail {


    final String SMTP_QQ = "";
    final String SMTP_163 = "smtp.163.com";
    
    final int SMTP_PORT = 465;
    final String sendHost = "smtp.xx.com";
    final String sendMail = "xxx@xxx.com";
    final String sendPwd = "xxxx";
    
    public void sendVerficaionUrlBySelf(String receiveMail, String url)throws Exception{
        
        String subject = "邮箱验证 Email verification";
        String content ="点击以下链接激活:(如果无法直接打开,可将它复制到浏览器地址栏访问)" +
                    "<br/>" +
                    "Click the following link to activate: (if not directly open, please copy it to your browser's address bar to access)" +
                    "<br/>" +
                    "<a href='"+url+"'>"+url+"</a>";
        
        baseSend(sendHost, sendMail, sendPwd, receiveMail, subject, content);
    }
    
    public void sendVerficaionUrlBySelfSSL(String receiveMail, String url)throws Exception{
        
        String subject = "邮箱验证 Email verification";
        String content ="点击以下链接激活:(如果无法直接打开,可将它复制到浏览器地址栏访问)" +
                    "<br/>" +
                    "Click the following link to activate: (if not directly open, please copy it to your browser's address bar to access)" +
                    "<br/>" +
                    "<a href='"+url+"'>"+url+"</a>";
        
        sslSend(sendHost, sendMail, sendPwd, receiveMail, subject, content);
    }
    
    
    
    private Properties baseProperties(String myEmailSMTPHost){
     // 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
        props.setProperty("mail.host", myEmailSMTPHost);        // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 请求认证,参数名称与具体实现有关
        
        
        return props;
    }
    
    private Properties sslProperties(String myEmailSMTPHost){
     // 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtps");   // 使用的ssl协议(JavaMail规范要求)
        props.setProperty("mail.smtps.host", myEmailSMTPHost);        // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtps.auth", "true");            // 请求认证,参数名称与具体实现有关
        
        return props;
    }
    
    private MimeMessage createMiMsg(Session session, String sendMail, String receiveMail, String subject, String content) throws Exception {


        MimeMessage miMsg = new MimeMessage(session);


        // 发件人
        miMsg.setFrom(new InternetAddress(sendMail, "SIRUI", "UTF-8"));


        // To: 收件人(可以增加多个收件人、抄送、密送)
        miMsg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8"));


        // 邮件主题
        miMsg.setSubject(subject, "UTF-8");


        // 邮件正文(可以使用html标签)
        miMsg.setContent(content, "text/html;charset=UTF-8");


        // 发件时间
        miMsg.setSentDate(new Date());


        // 保存设置
        miMsg.saveChanges();


        return miMsg;
        
    }
    
    private void baseSend(String smtphost, String sendMail, String sendPwd, String receiveMail, String subject,String content) throws Exception{
        
     // 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getDefaultInstance(baseProperties(smtphost));
     // 设置为debug模式, 可以查看详细的发送 log
        session.setDebug(true);
        
        
        MimeMessage mimsg = createMiMsg(session, sendMail, receiveMail, subject, content);
        
     // 获取邮件传输对象
        Transport transport = session.getTransport();
//        使用 邮箱账号 和 密码 连接邮件服务器
        //    这里认证的邮箱必须与 message 中的发件人邮箱一致,否则报错
//        transport.connect(sendMail, sendPwd);
        //ssl
        transport.connect(sendMail, sendPwd);
     // 发送邮件, 发到所有的收件地址, getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
//        transport.sendMessage(mimsg, mimsg.getAllRecipients());
        transport.sendMessage(mimsg, mimsg.getRecipients(MimeMessage.RecipientType.TO));
        // 关闭连接
        transport.close();
    }
    
    private void sslSend(String smtphost, String sendMail, String sendPwd, String receiveMail, String subject,String content) throws Exception{
        
        // 根据配置创建会话对象, 用于和邮件服务器交互
           Session session = Session.getDefaultInstance(sslProperties(smtphost));
        // 设置为debug模式, 可以查看详细的发送 log
           session.setDebug(true);
           
           
           MimeMessage mimsg = createMiMsg(session, sendMail, receiveMail, subject, content);
           
        // 获取邮件传输对象
           Transport transport = session.getTransport();
//           使用 邮箱账号 和 密码 连接邮件服务器
           //    这里认证的邮箱必须与 message 中的发件人邮箱一致,否则报错
//           transport.connect(sendMail, sendPwd);
           //ssl
           transport.connect(smtphost, SMTP_PORT,sendMail, sendPwd);
        // 发送邮件, 发到所有的收件地址, getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
//           transport.sendMessage(mimsg, mimsg.getAllRecipients());
           transport.sendMessage(mimsg, mimsg.getRecipients(MimeMessage.RecipientType.TO));
           // 关闭连接
           transport.close();
       }
}

简介: 类似与http与 https协议,  邮件系统也有 ssl, 而明文的smtp端口是25, 加密的是465.

当用465时候,出现此报错: unable to find valid certification path to requested target 

仔细一看, 是找不到证书, 问题很大,证书好像很遥远。。于是找到一个获取证书的类

import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.security.KeyStore;  
import java.security.MessageDigest;  
import java.security.cert.CertificateException;  
import java.security.cert.X509Certificate;  
  
import javax.net.ssl.SSLContext;  
import javax.net.ssl.SSLException;  
import javax.net.ssl.SSLSocket;  
import javax.net.ssl.SSLSocketFactory;  
import javax.net.ssl.TrustManager;  
import javax.net.ssl.TrustManagerFactory;  
import javax.net.ssl.X509TrustManager; 

public class InstallCert {
    public static void main(String[] args) throws Exception {  
        String host;  
        int port;  
        char[] passphrase;  
        if ((args.length == 1) || (args.length == 2)) {  
            String[] c = args[0].split(":");  
            host = c[0];  
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);  
            String p = (args.length == 1) ? "changeit" : args[1];  
            passphrase = p.toCharArray();  
        } else {  
            System.out  
                    .println("Usage: java InstallCert <host>[:port] [passphrase]");  
            return;  
        }  
  
        File file = new File("jssecacerts");  
        if (file.isFile() == false) {  
            char SEP = File.separatorChar;  
            File dir = new File(System.getProperty("java.home") + SEP + "lib"  
                    + SEP + "security");  
            file = new File(dir, "jssecacerts");  
            if (file.isFile() == false) {  
                file = new File(dir, "cacerts");  
            }  
        }  
        System.out.println("Loading KeyStore " + file + "...");  
        InputStream in = new FileInputStream(file);  
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());  
        ks.load(in, passphrase);  
        in.close();  
  
        SSLContext context = SSLContext.getInstance("TLS");  
        TrustManagerFactory tmf = TrustManagerFactory  
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());  
        tmf.init(ks);  
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf  
                .getTrustManagers()[0];  
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);  
        context.init(null, new TrustManager[] { tm }, null);  
        SSLSocketFactory factory = context.getSocketFactory();  
  
        System.out  
                .println("Opening connection to " + host + ":" + port + "...");  
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);  
        socket.setSoTimeout(10000);  
        try {  
            System.out.println("Starting SSL handshake...");  
            socket.startHandshake();  
            socket.close();  
            System.out.println();  
            System.out.println("No errors, certificate is already trusted");  
        } catch (SSLException e) {  
            System.out.println();  
            e.printStackTrace(System.out);  
        }  
  
        X509Certificate[] chain = tm.chain;  
        if (chain == null) {  
            System.out.println("Could not obtain server certificate chain");  
            return;  
        }  
  
        BufferedReader reader = new BufferedReader(new InputStreamReader(  
                System.in));  
  
        System.out.println();  
        System.out.println("Server sent " + chain.length + " certificate(s):");  
        System.out.println();  
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");  
        MessageDigest md5 = MessageDigest.getInstance("MD5");  
        for (int i = 0; i < chain.length; i++) {  
            X509Certificate cert = chain[i];  
            System.out.println(" " + (i + 1) + " Subject "  
                    + cert.getSubjectDN());  
            System.out.println("   Issuer  " + cert.getIssuerDN());  
            sha1.update(cert.getEncoded());  
            System.out.println("   sha1    " + toHexString(sha1.digest()));  
            md5.update(cert.getEncoded());  
            System.out.println("   md5     " + toHexString(md5.digest()));  
            System.out.println();  
        }  
  
        System.out  
                .println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");  
        String line = reader.readLine().trim();  
        int k;  
        try {  
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;  
        } catch (NumberFormatException e) {  
            System.out.println("KeyStore not changed");  
            return;  
        }  
  
        X509Certificate cert = chain[k];  
        String alias = host + "-" + (k + 1);  
        ks.setCertificateEntry(alias, cert);  
  
        OutputStream out = new FileOutputStream("jssecacerts");  
        ks.store(out, passphrase);  
        out.close();  
  
        System.out.println();  
        System.out.println(cert);  
        System.out.println();  
        System.out  
                .println("Added certificate to keystore 'jssecacerts' using alias '"  
                        + alias + "'");  
    }  
  
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();  
  
    private static String toHexString(byte[] bytes) {  
        StringBuilder sb = new StringBuilder(bytes.length * 3);  
        for (int b : bytes) {  
            b &= 0xff;  
            sb.append(HEXDIGITS[b >> 4]);  
            sb.append(HEXDIGITS[b & 15]);  
            sb.append(' ');  
        }  
        return sb.toString();  
    }  
  
    private static class SavingTrustManager implements X509TrustManager {  
  
        private final X509TrustManager tm;  
        private X509Certificate[] chain;  
  
        SavingTrustManager(X509TrustManager tm) {  
            this.tm = tm;  
        }  
  
        public X509Certificate[] getAcceptedIssuers() {  
            throw new UnsupportedOperationException();  
        }  
  
        public void checkClientTrusted(X509Certificate[] chain, String authType)  
                throws CertificateException {  
            throw new UnsupportedOperationException();  
        }  
  
        public void checkServerTrusted(X509Certificate[] chain, String authType)  
                throws CertificateException {  
            this.chain = chain;  
            tm.checkServerTrusted(chain, authType);  
        }  
    } 
}

神器啊, 把它保存到D盘

编译它: javac InstallCert , 会在D盘看到生成好的class

执行:java InstallCert smtp.xxx.com:465 changeit

changeit是密码, main函数里可以修改

根据运行提示信息,输入1,回车,在当前目录下生成名为: jssecacerts 的证书

将证书放置到$JAVA_HOME/jre/lib/security目录下, 切记该JDK的jre是工程所用的环境!!!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值