JavaMail SSL TLS 发送邮件

话不多说,JavaMail实现的SSL/TLS发送邮件,网上找的一段代码用TLS发送邮件ok,但是SSL一直不成功,查看资料之后修改代码发送成功,直接上代码如下:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

package adam.app.controller;

import com.sun.mail.util.MailSSLSocketFactory;
import java.security.GeneralSecurityException;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.SendFailedException;
import javax.mail.Authenticator;

public class EmailUtil {

    private final static String default_charset = "UTF-8";

    public static enum EncryptionTypes{
        Default, TLS, SSL
    }

    private String mail_host = "";
    private int mail_port = 25;
    private int encryptionType = EncryptionTypes.Default.ordinal();
    private boolean auth = false;
    private String mail_host_account = "";
    private String mail_host_password = "";
    private boolean isHtml = false;

    public EmailUtil(String mail_host,int mail_port, int encryptionType, boolean auth, String account, String password, boolean isHtml){
        this.mail_host = mail_host;
        this.mail_port = mail_port;
        this.encryptionType = encryptionType;
        this.auth = auth;
        this.mail_host_account = account;
        this.mail_host_password = password;
        this.isHtml = isHtml;
    }

    public void sendEmail(String senderAddress, String senderName, String receiverAddress, String sub, String msg, Collection attachments) throws Exception {
        String[] address = receiverAddress.split(";");
        List recipients = new ArrayList();
        for(int i=0;i
   
   
    
    0){
                recipients.add(address[i]);
            }
        }
        this.sendEmail(senderAddress, senderName, recipients, sub, msg, attachments);
    }

    public void sendEmail(String senderAddress, String senderName, List recipients, String sub, String msg, Collection attachments) throws SendFailedException {
        Transport transport = null;
        try {
            Properties props = this.getProperties();
            Session session = this.getSession(props);
            MimeMessage message = new MimeMessage(session);
            if(this.getDefaultIsHtml()){
                message.addHeader("Content-type", "text/html");
            }else{
                message.addHeader("Content-type", "text/plain");
            }

            message.setSubject(sub,default_charset);
            message.setFrom(new InternetAddress(senderAddress, senderName));
            for (Iterator it = recipients.iterator(); it.hasNext();) {
                String email = (String) it.next();
                message.addRecipients(Message.RecipientType.TO, email);
            }

            Multipart mp = new MimeMultipart();
            MimeBodyPart contentPart = new MimeBodyPart();
            if(this.getDefaultIsHtml()){
                contentPart.setContent("
    
    "+msg,"text/html;charset="+default_charset);
            }else{
                contentPart.setText(msg,default_charset);
            }
            mp.addBodyPart(contentPart);

            if(attachments!=null){
                MimeBodyPart attachPart;
                for(Iterator it = attachments.iterator(); it.hasNext();){
                    attachPart = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(it.next().toString().trim());
                    attachPart.setDataHandler(new DataHandler(fds));
                    if(fds.getName().indexOf("$")!=-1){
                        attachPart.setFileName(fds.getName().substring(fds.getName().indexOf("$")+1,fds.getName().length()));
                    }else{
                        attachPart.setFileName(fds.getName());
                    }
                    mp.addBodyPart(attachPart);
                }
            }

            message.setContent(mp);
            message.setSentDate(new Date());
            if(this.getDefaultEncryptionType() == EncryptionTypes.SSL.ordinal()){
                Transport.send(message);
            }else{
                transport = session.getTransport("smtp");
                transport.connect(this.mail_host,
                        this.mail_port,
                        this.mail_host_account,
                        this.mail_host_password);
                transport.sendMessage(message, message.getAllRecipients());
            }
        } catch (Exception e) {
            System.out.println("send mail error");
            throw new SendFailedException(e.toString());
        } finally{
            if(transport!=null){
                try{
                    transport.close();
                }catch(Exception ex){
                }
            }
        }
    }

    private Properties getProperties(){
        Properties props = System.getProperties();
        int defaultEncryptionType = this.getDefaultEncryptionType();
        if(defaultEncryptionType == EncryptionTypes.TLS.ordinal()){
            props.put("mail.smtp.auth", String.valueOf(this.auth));
            props.put("mail.smtp.starttls.enable", "true");
        }else if(defaultEncryptionType == EncryptionTypes.SSL.ordinal()){
            props.put("mail.smtp.host", this.mail_host);
            props.put("mail.smtp.socketFactory.port", this.mail_port);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.debug", "true");
            props.put("mail.smtp.auth", String.valueOf(this.auth));
            props.put("mail.smtp.port", this.mail_port);
            MailSSLSocketFactory sf = null;
            try {
                sf = new MailSSLSocketFactory();
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", sf);
        }else{
            props.put("mail.smtp.host", this.mail_host);
            props.put("mail.smtp.auth", String.valueOf(this.auth));
        }
        return props;
    }

    private Session getSession(Properties props){
        Session session = null;
        if(this.getDefaultEncryptionType() == EncryptionTypes.TLS.ordinal()){
            session = Session.getInstance(props);
        }else if(this.getDefaultEncryptionType() == EncryptionTypes.SSL.ordinal()){
            session = Session.getInstance(props, new MyAuthenticator(this.mail_host_account, this.mail_host_password));
        }else{
            session = Session.getDefaultInstance(props,null);
        }

        return session;
    }

    private boolean getDefaultIsHtml(){
        boolean rst = this.isHtml;
        return rst;
    }

    private class MyAuthenticator extends Authenticator{
        String user;
        String password;
        public MyAuthenticator(String user, String password){
            this.user = user;
            this.password = password;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(this.user, this.password);
        }
    }

    private int getDefaultEncryptionType(){
        int rst = this.encryptionType;
        if(this.encryptionType == EncryptionTypes.Default.ordinal()){
            if(this.mail_port==465){
                rst = EncryptionTypes.SSL.ordinal();
            }else if(this.mail_port==587){
                rst = EncryptionTypes.TLS.ordinal();
            }
        }
        return rst;
    }

    public static void main(String[] args){
        EmailUtil email = new EmailUtil("smtp.exmail.qq.com", 25, 1, true, "sendemail","password",true);
        Collection col = new ArrayList();
        try{
            email.sendEmail(
                    "sendemail",
                    "sendemail",
                    "receiveremail",
                    "test",
                    "
    
    test",
                    col);
            System.out.println("send out successfully");



//        EmailUtil email = new EmailUtil("smtp.exmail.qq.com", 465, 2, true, "sendemail","password",true);
//        Collection col = new ArrayList();
//        try{
//            email.sendEmail(
//                    "sendemail",
//                    "sendemail",
//                    "receiveremail",
//                    "test",
//                    "
    
    test",
//                    col);
//            System.out.println("send out successfully");
        }catch(Exception ex){
            ex.printStackTrace();
            System.out.println("send fail");
        }
    }
}
   
   

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值