zoukankan      html  css  js  c++  java
  • java邮件工具类【最终版】

    http://www.xdemo.org/java-mail/

    对比链接中,添加了抄送和暗抄送功能(已解决,如图代码:抄送不能多个用户,会报错,未解之谜)

    sendHtmlmail方法可以发送附件以及html内容(ps:table标签可用),但是内容中链接则会被163邮箱认定为垃圾邮件

    maven依赖:

    <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>javax.mail-api</artifactId>
                <version>1.5.2</version>
            </dependency>
            <dependency>
                <groupId>com.sun.mail</groupId>
                <artifactId>dsn</artifactId>
                <version>1.5.2</version>
            </dependency>

    Email PO类:

    package common;
    
    /**
     * Created by zipon on 2017/4/21.
     */
    import java.io.File;
    import java.security.GeneralSecurityException;
    import java.util.List;
    import java.util.Properties;
    
    import com.sun.mail.util.MailSSLSocketFactory;
    
    public class Email {
        // 发送邮件的服务器的IP和端口
        private String mailServerHost;
        private String mailServerPort;
        // 邮件发送者的地址
        private String fromAddress;
        //邮件发送者名称
        private String fromNickName;
        // 邮件接收者的地址
        private String toAddress;
        // 邮件抄送者地址
        private String CCAddress;
        //邮件暗抄送地址
        private String BCCAddress;
        // 登陆邮件发送服务器的用户名和密码
        private String userName;
        private String password;
        // 是否需要身份验证
        private boolean validate = false;
        // 邮件主题
        private String subject;
        // 邮件的文本内容
        private String content;
        // 邮件附件的文件名
        private List<File> attachments;
    
        /**
         * 获得邮件会话属性
         * @throws GeneralSecurityException
         */
        public Properties getProperties() throws GeneralSecurityException {
            Properties props = new Properties();
            props.put("mail.smtp.host", this.mailServerHost);
            props.put("mail.smtp.port", this.mailServerPort);
            props.put("mail.smtp.auth", validate ? "true" : "false");
            //SSL
            /*MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.transport.protocol", "smtps");
            props.put("mail.smtp.starttls.enable", "true");*/
            return props;
        }
    
        public String getMailServerHost() {
            return mailServerHost;
        }
    
        public void setMailServerHost(String mailServerHost) {
            this.mailServerHost = mailServerHost;
        }
    
        public String getMailServerPort() {
            return mailServerPort;
        }
    
        public void setMailServerPort(String mailServerPort) {
            this.mailServerPort = mailServerPort;
        }
    
        public boolean isValidate() {
            return validate;
        }
    
        public void setValidate(boolean validate) {
            this.validate = validate;
        }
    
        public List<File> getAttachments() {
            return attachments;
        }
    
        public void setAttachments(List<File> attachments) {
            this.attachments = attachments;
        }
    
        public String getFromAddress() {
            return fromAddress;
        }
    
        public void setFromAddress(String fromAddress) {
            this.fromAddress = fromAddress;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getToAddress() {
            return toAddress;
        }
    
        public void setToAddress(String toAddress) {
            this.toAddress = toAddress;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getSubject() {
            return subject;
        }
    
        public void setSubject(String subject) {
            this.subject = subject;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String textContent) {
            this.content = textContent;
        }
    
        public String getFromNickName() {
            return fromNickName;
        }
    
        public void setFromNickName(String fromNickName) {
            this.fromNickName = fromNickName;
        }
    
        public String getCCAddress() {
            return CCAddress;
        }
    
        public void setCCAddress(String CCAddress) {
            this.CCAddress = CCAddress;
        }
    
        public String getBCCAddress() {
            return BCCAddress;
        }
    
        public void setBCCAddress(String BCCAddress) {
            this.BCCAddress = BCCAddress;
        }
    }

    Email 授权工具类:

    package common;
    
    /**
     * Created by zipon on 2017/4/21.
     */
    import javax.mail.Authenticator;
    import javax.mail.PasswordAuthentication;
    
    public class MailAuthenticator extends Authenticator{
    
        String userName = null;
        String password = null;
    
        public MailAuthenticator() {
        }
    
        public MailAuthenticator(String userName, String password) {
            this.userName = userName;
            this.password = password;
        }
    
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    
    }

    Email 发送工具类以及测试main:

    package common;
    
    /**
     * Created by zipon on 2017/4/21.
     */
    import java.io.File;
    import java.io.UnsupportedEncodingException;
    import java.security.GeneralSecurityException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.Properties;
    
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Address;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    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 <a href="http://www.xdemo.org">xdemo.org</a>
     *
     */
    public class MailSender {
        /**
         * 以文本格式发送邮件
         *
         * @param mail
         * 待发送的邮件的信息
         * @throws GeneralSecurityException
         */
        public boolean sendTextMail(Email mail) throws GeneralSecurityException {
            // 判断是否需要身份认证
            MailAuthenticator authenticator = null;
            Properties pro = mail.getProperties();
            if (mail.isValidate()) {
                // 如果需要身份认证,则创建一个密码验证器
                authenticator = new MailAuthenticator(mail.getUserName(), mail.getPassword());
            }
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session
            Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
            try {
                // 根据session创建一个邮件消息
                Message mailMessage = new MimeMessage(sendMailSession);
                // 创建邮件发送者地址
                Address from = new InternetAddress(mail.getFromAddress());
                // 设置邮件消息的发送者
                mailMessage.setFrom(from);
                // 创建邮件的接收者地址,并设置到邮件消息中
                Address to = new InternetAddress(mail.getToAddress());
                mailMessage.setRecipients(Message.RecipientType.TO, to);
                //创建邮件抄送者地址
                if(mail.getCCAddress()!=null) {
                    //Address cc = new InternetAddress(mail.getCCAddress());
                    mailMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.getCCAddress()));
                }
                //创建邮件暗抄送者地址
                if(mail.getBCCAddress()!=null) {
                    //Address bcc = new InternetAddress(mail.getBCCAddress());
                    mailMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.getBCCAddress()));
                }
                // 设置邮件消息的主题
                mailMessage.setSubject(mail.getSubject());
                // 设置邮件消息发送的时间s
                mailMessage.setSentDate(new Date());
                // 设置邮件消息的主要内容
                String mailContent = mail.getContent();
                mailMessage.setText(mailContent);
                // 发送邮件
                Transport.send(mailMessage);
                return true;
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
            return false;
        }
    
        /**
         * 以HTML格式发送邮件
         *
         * @param mail
         *            待发送的邮件信息
         * @throws GeneralSecurityException
         * @throws UnsupportedEncodingException
         */
        public boolean sendHtmlMail(Email mail) throws GeneralSecurityException, UnsupportedEncodingException {
            // 判断是否需要身份认证
            MailAuthenticator authenticator = null;
            Properties props = mail.getProperties();
            // 如果需要身份认证,则创建一个密码验证器
            if (mail.isValidate()) {
                authenticator = new MailAuthenticator(mail.getUserName(), mail.getPassword());
            }
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session
            Session sendMailSession = Session.getDefaultInstance(props, authenticator);
            sendMailSession.setDebug(true);
            try {
                // 根据session创建一个邮件消息
                Message mailMessage = new MimeMessage(sendMailSession);
                // 创建邮件发送者地址
                Address from = new InternetAddress(mail.getFromAddress(),mail.getFromNickName()==null?"":mail.getFromNickName());
                // 设置邮件消息的发送者
                mailMessage.setFrom(from);
                // 创建邮件的接收者地址,并设置到邮件消息中,可以设置多个收件人,逗号隔开
                // Message.RecipientType.TO属性表示接收者的类型为TO,CC表示抄送,BCC暗送
                mailMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail.getToAddress()));
    
                //创建邮件抄送者地址
                if(mail.getCCAddress()!=null) {
                    //Address cc = new InternetAddress(mail.getCCAddress());
                    mailMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.getCCAddress()));
                }
                //创建邮件暗抄送者地址s
                if(mail.getBCCAddress()!=null) {
                    //Address bcc = new InternetAddress(mail.getBCCAddress());
                    mailMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.getBCCAddress()));
                }
                // 设置邮件消息的主题
                mailMessage.setSubject(mail.getSubject());
                // 设置邮件消息发送的时间
                mailMessage.setSentDate(new Date());
    
                // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
                Multipart mainPart = new MimeMultipart();
                // 创建一个包含HTML内容的MimeBodyPart
                MimeBodyPart html = new MimeBodyPart();
                // 设置HTML内容
                html.setContent(mail.getContent(), "text/html; charset=utf-8");
                mainPart.addBodyPart(html);
    
                // 设置信件的附件(用本地上的文件作为附件)
                FileDataSource fds=null;
                DataHandler dh=null;
                if (mail.getAttachments()!=null) {
                    for (File file : mail.getAttachments()) {
                        html = new MimeBodyPart();
                        fds = new FileDataSource(file);
                        dh = new DataHandler(fds);
                        html.setFileName(file.getName());
                        html.setDataHandler(dh);
                        mainPart.addBodyPart(html);
                    }
                }
    
                // 将MiniMultipart对象设置为邮件内容
                mailMessage.setContent(mainPart);
                mailMessage.saveChanges();
    
                // 发送邮件
                Transport.send(mailMessage);
                return true;
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
            return false;
        }
    
        public static void main(String[] args) throws GeneralSecurityException, UnsupportedEncodingException {
    //        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    //        Properties props = System.getProperties();
    //        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    //
    //        props.setProperty("mail.smtp.socketFactory.fallback", "false");
    //        props.setProperty("mail.smtp.socketFactory.port", "465");
            // 这个类主要是设置邮件
            Email mailInfo = new Email();
            mailInfo.setCCAddress("xxxx@qq.com");
            mailInfo.setMailServerHost("smtp.163.com");
            mailInfo.setMailServerPort("25");
            mailInfo.setValidate(true);
            mailInfo.setFromNickName("xxx");
            mailInfo.setUserName("xxx@163.com"); // 实际发送者
            mailInfo.setPassword("xxx");// 您的邮箱密码/授权码
            mailInfo.setFromAddress("xxx@163.com"); // 设置发送人邮箱地址
            mailInfo.setToAddress("xxx@qq.com,xxx@qq.com"); // 设置接受者邮箱地址
            mailInfo.setSubject("【镁锭项目计划回归】按照这次的来。反馈");
            mailInfo.setContent("已完成!反馈。这次一定行!<table><tr><td>第一行第一列</td><td>第二行第二列</td></tr></table>");
    //        mailInfo.setAttachments(new ArrayList<File>(){
    //            {
    //                add(new File("D:\driver\geckodriver.exe"));
    //                add(new File("D:\driver\chromedriver.exe"));
    //            }
    //        });
            // 这个类主要来发送邮件
            MailSender sms = new MailSender();
            //sms.sendTextMail(mailInfo); // 发送文体格式
            sms.sendHtmlMail(mailInfo); // 发送html格式,需要发送附件或者html(一般是table可用,链接好像不行)时,选择这个
        }
    }
  • 相关阅读:
    pl/sql developer中如何导出oracle数据库结构? 参考文章一
    ORACLE知识点整理之一
    WebService之第一天
    Eclipse中,open declaration;open implementation;open super implementation的区别
    Maven 手动添加 JAR 包到本地仓库
    clipse maven 项目 出现红色叹号 解决方法
    eclipse快捷键设置
    Hibernate3--快速入门--第一天
    C++ 虚函数表解析
    c++ primer复习(二)
  • 原文地址:https://www.cnblogs.com/zipon/p/6742955.html
Copyright © 2011-2022 走看看