• JavaMail


    JavaMail学习

    发送文本、发送html模板、群发、发送附件

    预备

    POM

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

    开始

    javax.mail.Session:上下文环境信息,如服务器的主机名、端口号、协议名称等  
    javax.mail.Message:邮件模型,发送邮件和接收邮件的媒介,封装了邮件的信息,如发件人、收件人、邮件标题、邮件内容等  
    javax.mail.Transport:连接邮件SMTP服务器,发送邮件  
    javax.mail.Store:连接邮件POP3、IMAP服务器,收取邮件  
    

    定义发送者信息mail.properties

    #Sender Auth
    username=发送者邮箱账户
    password=发送者邮箱密码
    
    #Sender Info
    from.address=发送者邮箱地址
    
    #Sender Server(这里测试发送者使用QQ邮箱)
    mail.smtp.host=smtp.qq.com
    mail.smtp.auth=true
    mail.smtp.port=587
    

    定义配置读取类MailConfig.java

    package com;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class MailConfig {
    
        private static Properties properties;
    
        public static Properties getProperties() {
            if (null == properties) {
                properties = new Properties();
                InputStream stream = MailDemo.class.getClassLoader().getResourceAsStream("mail.properties");
                try {
                    properties.load(stream);
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return properties;
        }
    
        public static String getHost() {
            return getProperties().getProperty("mail.smtp.host");
        }
    
        public static String getPort() {
            return getProperties().getProperty("mail.smtp.port");
        }
    
        public static String getUserName() {
            return getProperties().getProperty("username");
        }
    
        public static String getPassword() {
            return getProperties().getProperty("password");
        }
    
        public static String getFromAddress() {
            return getProperties().getProperty("from.address");
        }
    
        public static boolean getAuth() {
            return "true".equalsIgnoreCase(getProperties().getProperty("mail.smtp.auth"));
        }
    
    }
    

    定义认证类DemoAuthenticator.java

    /**
     * 认证信息
     */
    package com;
    
    import javax.mail.Authenticator;
    import javax.mail.PasswordAuthentication;
    
    public class DemoAuthenticator extends Authenticator {
        
        //用户名
        private String userName ;
        //用户密码
        private String password ;
    
        public DemoAuthenticator() {
        }
    
        public DemoAuthenticator(String username, String password) {
            this.userName = username;
            this.password = password;
        }
    
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    
    

    定义邮件内容类MailDetail.java

    /***
     * 邮件详情
     */
    
    package com;
    
    public class MailDetail {
    
        // 邮件接收者的地址
        private String toAddress;
        // 邮件主题
        private String subject;
        // 邮件的文本内容
        private String content;
        // 邮件附件的文件名
        private String[] attachFileNames;
    
        public String getToAddress() {
            return toAddress;
        }
    
        public void setToAddress(String toAddress) {
            this.toAddress = toAddress;
        }
    
        public String getSubject() {
            return subject;
        }
    
        public void setSubject(String subject) {
            this.subject = subject;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public String[] getAttachFileNames() {
            return attachFileNames;
        }
    
        public void setAttachFileNames(String[] attachFileNames) {
            this.attachFileNames = attachFileNames;
        }
    }
    

    定义发送器类

    package com;
    
    import java.io.IOException;
    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.Address;
    import javax.mail.BodyPart;
    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;
    import javax.mail.internet.MimeUtility;
    
    /**
     * 简单邮件(不带附件的邮件)发送器
     */
    public class SimpleMailSender {
    
        /**
         * 以文本格式发送邮件
         * 
         * @param detail
         *            待发送的邮件的信息
         */
        public static boolean sendTextMail(MailDetail detail) {
            // 判断是否需要身份认证
            DemoAuthenticator authenticator = null;
            Properties pro = MailConfig.getProperties();
            System.out.println("是否需要验证:" + (MailConfig.getAuth() == true));
            if (MailConfig.getAuth()) {
                // 如果需要身份认证,则创建一个密码验证器
                authenticator = new DemoAuthenticator(MailConfig.getUserName(), MailConfig.getPassword());
            }
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session
            Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
            try {
                // 根据session创建一个邮件消息
                Message mailMessage = new MimeMessage(sendMailSession);
                // 创建邮件发送者地址
                Address from = new InternetAddress(MailConfig.getFromAddress());
                // 设置邮件消息的发送者
                mailMessage.setFrom(from);
                // 创建邮件的接收者地址,并设置到邮件消息中
                Address to = new InternetAddress(detail.getToAddress());
                mailMessage.setRecipient(Message.RecipientType.TO, to);
                //循环add可以实现群发
                //mailMessage.addRecipient(Message.RecipientType.TO, to);
                // 设置邮件消息的主题
                mailMessage.setSubject(detail.getSubject());
                // 设置邮件消息发送的时间
                mailMessage.setSentDate(new Date());
                // 设置邮件消息的主要内容
                String mailContent = detail.getContent();
    
                mailMessage.setText(mailContent);
                mailMessage.saveChanges();
                // 发送邮件方式一
                /*
                 * mailMessage.saveChanges(); // implicit with send() Transport
                 * transport = sendMailSession.getTransport("smtp");
                 * transport.connect(MailProperties.getHost(),
                 * MailProperties.getUserName(), MailProperties.getPassword());
                 * transport.sendMessage(mailMessage,
                 * mailMessage.getAllRecipients()); transport.close();
                 */
                // 发送邮件方式二
                Transport.send(mailMessage);
                return true;
            } catch (MessagingException ex) {
                ex.printStackTrace();
            }
            return false;
        }
    
        /**
         * 以HTML格式发送邮件
         * 
         * @param detail
         *            待发送的邮件信息
         */
        public static boolean sendHtmlMail(MailDetail detail) {
            // 判断是否需要身份认证
            DemoAuthenticator authenticator = null;
            Properties pro = MailConfig.getProperties();
            // 如果需要身份认证,则创建一个密码验证器
            if (MailConfig.getAuth()) {
                authenticator = new DemoAuthenticator(MailConfig.getUserName(), MailConfig.getPassword());
            }
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session
            Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
            try {
                // 根据session创建一个邮件消息
                Message mailMessage = new MimeMessage(sendMailSession);
                // 创建邮件发送者地址
                Address from = new InternetAddress(MailConfig.getFromAddress());
                // 设置邮件消息的发送者
                mailMessage.setFrom(from);
                // 创建邮件的接收者地址,并设置到邮件消息中
                Address to = new InternetAddress(detail.getToAddress());
                // Message.RecipientType.TO属性表示接收者的类型为TO
                mailMessage.setRecipient(Message.RecipientType.TO, to);
                // 设置邮件消息的主题
                mailMessage.setSubject(detail.getSubject());
                // 设置邮件消息发送的时间
                mailMessage.setSentDate(new Date());
                // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
                Multipart mainPart = new MimeMultipart();
                // 创建一个包含HTML内容的MimeBodyPart
                BodyPart html = new MimeBodyPart();
                // 设置HTML内容
                html.setContent(detail.getContent(), "text/html; charset=utf-8");
                mainPart.addBodyPart(html);
                // 添加附件
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.attachFile("C:\Apps\QQ\Plugin\Com.Tencent.QQVip\Misc\CustomFont\101\qie17b.png");
                mimeBodyPart.setFileName(MimeUtility.encodeWord("测试附件.png"));
                mainPart.addBodyPart(mimeBodyPart);
                // 将MiniMultipart对象设置为邮件内容
                mailMessage.setContent(mainPart);
                mailMessage.saveChanges();
                // 发送邮件
                Transport.send(mailMessage);
                return true;
            } catch (MessagingException ex) {
                ex.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    }
    

    测试Demo

    public static void main(String[] args) {
    
            MailDetail detail = new MailDetail();
            detail.setToAddress(接收者邮箱地址);
            detail.setSubject("测试邮箱标题WithHtml");
            detail.setContent(readTemplate());
    
            //发送文本
            boolean result = SimpleMailSender.sendTextMail(detail);
            //发送html格式
            //boolean result = SimpleMailSender.sendHtmlMail(detail);
            // 发送文体格式
            if(result){
                System.out.println("发送成功...");
            }else{
                System.out.println("发送失败...");
            }
        }
    

    附加(读取文本)

        private static String readTemplate() {
            StringBuilder builder = new StringBuilder();
            String encoding = "UTF-8";
            InputStreamReader read = null;
            try {
                read = new InputStreamReader(MailDemo.class.getClassLoader().getResourceAsStream("temp.html"), encoding); 
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    builder.append(lineTxt);
                }
                read.close();
            } catch (Exception e) {
                System.out.println("读取文件内容出错");
                e.printStackTrace();
            }
            return builder.toString();
        }
    
    
  • 相关阅读:
    数据库备份 DBS(Database Backup),知识点
    关系型数据库 RDS(Relational Database Service),知识点
    对象存储服务 OSS(Object Storage Service),知识点(待补充上仓库代码)
    Java 为什么需要包装类,如何使用包装类?
    for each 语句
    缓存中,2个注解:@cacheable 与 @cacheput 的区别
    微信小程序,相关代码
    微信小程序中的事件
    通俗易懂:索引、单列索引、复合索引、主键、唯一索引、聚簇索引、非聚簇索引、唯一聚簇索引 的区别与联系
    MySQL 的各种 join
  • 原文地址:https://www.cnblogs.com/vmask/p/8728680.html
Copyright © 2020-2023  润新知