• java发送email文件


    1. 加入jar包

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.5.0-b01</version>
    </dependency>

    2.编码如下:

    方式1:

    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class EmailTest {
        
        public static String myEmailAccount = "mabiao008@126.com"; // 发件人邮箱地址
        public static String myEmailPassword = "XXXXXX"; // 发件人邮箱密码
        public static String myEmailSMTPHost = "smtp.126.com";
        public static String receiveMailAccount = "360227812@qq.com"; // 收件人邮箱地址
        public static void main(String[] args) throws Exception {
            // 1. 创建参数配置, 用于连接邮件服务器的参数配置
            Properties props = new Properties();                    // 参数配置
            props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
            props.setProperty("mail.host", myEmailSMTPHost);        // 发件人的邮箱的 SMTP 服务器地址
            props.setProperty("mail.smtp.auth", "true");
            // 2. 根据配置创建会话对象, 用于和邮件服务器交互
            Session session = Session.getDefaultInstance(props);
            session.setDebug(true); // 设置为debug模式, 如果值为true则可以查看详细的发送 log
            // 3. 创建一封邮件
            MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount);
            // 4. 根据 Session 获取邮件传输对象
            Transport transport = session.getTransport();
            // 5. 使用 邮箱账号 和 密码 连接邮件服务器--这里认证的邮箱必须与 message 中的发件人邮箱一致,否则报错
            transport.connect(myEmailAccount, myEmailPassword);
            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());
            // 7. 关闭连接
            transport.close();
        }
    
        /**
         * 创建一封只包含文本的简单邮件
         *
         * @param session 和服务器交互的会话
         * @param sendMail 发件人邮箱
         * @param receiveMail 收件人邮箱
         * @return
         * @throws Exception
         */
        public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception {
            // 1. 创建一封邮件
            MimeMessage message = new MimeMessage(session);
            // 2. From: 发件人
            message.setFrom(new InternetAddress(sendMail, "mabiao008", "UTF-8"));
            // 3. To: 收件人(可以增加多个收件人、抄送、密送)
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "测试", "UTF-8"));
            // 4. Subject: 邮件主题
            message.setSubject("测试邮件", "UTF-8");
            // 5. Content: 邮件正文(可以使用html标签)
            message.setContent("<font color=\"red\">欢迎光临我的博客: http://www.cnblogs.com/mabiao008/ </font>", "text/html;charset=UTF-8");
            // 6. 设置发件时间
            message.setSentDate(new Date());
            // 7. 保存设置
            message.saveChanges();
            return message;
        }
    }

    方式2:

    需要3个java文件支持

    (1)MailSenderInfo.java

    import java.util.Properties;
    
    /** 
     * 发送邮件需要使用的基本信息  
     * @author mabiao
     */
    public class MailSenderInfo {
        // 发送邮件的服务器的IP  
        private String mailServerHost;      
        // 发送邮件的服务器的端口      
        private String mailServerPort = "25";      
        // 邮件发送者的地址      
        private String fromAddress;      
        // 邮件接收者的地址      
        private String[] toAddress;  
        // 邮件密送接收者的地址  
        private String[] toBlindCarbonCopyAddress;  
        // 邮件抄送接收者的地址  
        private String[] toCarbonCopyAddress;  
        // 登陆邮件发送服务器的用户名  
        private String userName;  
        // 登陆邮件发送服务器的密码      
        private String password;      
        // 是否需要身份验证      
        private boolean validate = false;      
        // 邮件主题      
        private String subject;      
        // 邮件的文本内容      
        private String content;      
        // 邮件附件的文件名      
        private String[] attachFileNames;  
          
        /** 
         * 获得邮件会话属性 
         */  
        public Properties getProperties() {  
            Properties pro = new Properties();  
            pro.put("mail.smtp.host", this.mailServerHost);  
            pro.put("mail.smtp.port", this.mailServerPort);  
            pro.put("mail.smtp.auth", validate ? "true" : "false");  
            return pro;  
        }  
          
        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 String getFromAddress() {  
            return fromAddress;  
        }  
        public void setFromAddress(String fromAddress) {  
            this.fromAddress = fromAddress;  
        }  
        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 getPassword() {  
            return password;  
        }  
        public void setPassword(String password) {  
            this.password = password;  
        }  
        public boolean isValidate() {  
            return validate;  
        }  
        public void setValidate(boolean validate) {  
            this.validate = validate;  
        }  
        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;  
        }  
      
        public String[] getToBlindCarbonCopyAddress() {  
            return toBlindCarbonCopyAddress;  
        }  
      
        public void setToBlindCarbonCopyAddress(String[] toBlindCarbonCopyAddress) {  
            this.toBlindCarbonCopyAddress = toBlindCarbonCopyAddress;  
        }  
      
        public String[] getToCarbonCopyAddress() {  
            return toCarbonCopyAddress;  
        }  
      
        public void setToCarbonCopyAddress(String[] toCarbonCopyAddress) {  
            this.toCarbonCopyAddress = toCarbonCopyAddress;  
        }  
    }

    (2).MyAuthenticator.java

    import javax.mail.Authenticator;
    import javax.mail.PasswordAuthentication;
    
    public class MyAuthenticator extends Authenticator {
        private String username;  
        private String password;  
        public MyAuthenticator(){  
              
        }  
          
        public MyAuthenticator(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;  
        }  
    }

    (3).SimpleMailSender.java

    import java.io.UnsupportedEncodingException;  
    import java.util.Date;  
    import java.util.Properties;  
    import javax.activation.DataHandler;  
    import javax.activation.DataSource;  
    import javax.activation.FileDataSource;  
    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.AddressException;  
    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 senderInfo 待发送的邮件的信息  
         * @return 
         */  
        public static boolean sendMail(MailSenderInfo senderInfo){  
            boolean flag = false;  
              
            // 判断是否需要身份验证  
            MyAuthenticator authenticator = null;  
            Properties props = senderInfo.getProperties();  
            if(senderInfo.isValidate()){  
                // 如果需要身份认证,则创建一个密码验证器     
                authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword());  
            }  
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session  
            Session sendMailSession = Session.getDefaultInstance(props, authenticator);  
              
            try {  
                // 根据session创建一个邮件消息  
                Message sendMailMessage = new MimeMessage(sendMailSession);  
                // 创建邮件发送者地址  
                Address from = new InternetAddress(senderInfo.getFromAddress());  
                // 设置邮件消息的发送者  
                sendMailMessage.setFrom(from);  
                  
                // 创建邮件接收者地址  
                String[] tos = senderInfo.getToAddress();  
                if(tos != null && tos.length != 0){  
                    InternetAddress[] to = new InternetAddress[tos.length];  
                    // 设置邮件消息的发送者  
                    for (int i = 0; i < tos.length; i++) {  
                        to[i] = new InternetAddress(tos[i]);  
                    }  
                    sendMailMessage.setRecipients(Message.RecipientType.TO, to);  
                }  
                  
                // 设置邮件抄送者地址  
                String[] toCCs = senderInfo.getToCarbonCopyAddress();  
                if(toCCs != null && toCCs.length != 0){  
                    InternetAddress[] toCC = new InternetAddress[toCCs.length];  
                    // 设置邮件消息的发送者  
                    for (int i = 0; i < toCCs.length; i++) {  
                        toCC[i] = new InternetAddress(toCCs[i]);  
                    }  
                    sendMailMessage.addRecipients(Message.RecipientType.CC, toCC);  
                }  
                  
                // 设置邮件密送者地址  
                String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress();  
                if(toBCCs != null && toBCCs.length != 0){  
                    InternetAddress[] toBCC = new InternetAddress[toBCCs.length];  
                    for (int i = 0; i < toBCCs.length; i++) {  
                        toBCC[i] = new InternetAddress(toBCCs[i]);  
                    }  
                    sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC);  
                }  
                  
                // 设置邮件主题  
                sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B"));  
                // 设置邮件内容  
                //sendMailMessage.setText(senderInfo.getContent());  
                Multipart multipart = new MimeMultipart();  
                // 邮件文本内容  
                if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){  
                    BodyPart part = new MimeBodyPart();  
                    part.setContent(senderInfo.getContent(), "text/plain;charset=utf-8");//设置邮件文本内容  
                    multipart.addBodyPart(part);  
                }  
                  
                // 附件  
                String attachFileNames[] = senderInfo.getAttachFileNames();  
                int leng = attachFileNames == null ? 0 : attachFileNames.length;  
                for (int i = 0; i < leng; i++) {  
                    BodyPart part = new MimeBodyPart();  
                    // 根据文件名获取数据源  
                    DataSource dataSource = new FileDataSource(attachFileNames[i]);  
                    DataHandler dataHandler = new DataHandler(dataSource);  
                    // 得到附件本身并至入BodyPart  
                    part.setDataHandler(dataHandler);  
                    // 得到文件名同样至入BodyPart  
                    part.setFileName(MimeUtility.encodeText(dataSource.getName()));  
                    multipart.addBodyPart(part);  
                }  
                  
                sendMailMessage.setContent(multipart);  
                // 设置邮件发送的时间  
                sendMailMessage.setSentDate(new Date());  
                // 发送邮件  
                //Transport.send(sendMailMessage);  
                Transport transport = sendMailSession.getTransport("smtp");  
                transport.connect(senderInfo.getUserName(), senderInfo.getPassword());  
                transport.send(sendMailMessage,sendMailMessage.getAllRecipients());  
                transport.close();  
                  
                flag = true;  
            } catch (AddressException e) {  
                e.printStackTrace();  
            } catch (MessagingException e) {  
                e.printStackTrace();  
            } catch (UnsupportedEncodingException e) {  
                e.printStackTrace();  
            }  
              
            return flag;  
        }  
          
        public static boolean sendHtmlMail(MailSenderInfo senderInfo){  
            boolean flag = false;  
              
            // 判断是否需要身份验证  
            MyAuthenticator authenticator = null;  
            Properties props = senderInfo.getProperties();  
            if(senderInfo.isValidate()){  
                // 如果需要身份认证,则创建一个密码验证器     
                authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword());  
            }  
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session  
            Session sendMailSession = Session.getDefaultInstance(props, authenticator);  
              
            try {  
                // 根据session创建一个邮件消息  
                Message sendMailMessage = new MimeMessage(sendMailSession);  
                // 创建邮件发送者地址  
                Address from = new InternetAddress(senderInfo.getFromAddress());  
                // 设置邮件消息的发送者  
                sendMailMessage.setFrom(from);  
                  
                // 创建邮件接收者地址  
                String[] tos = senderInfo.getToAddress();  
                if(tos != null && tos.length != 0){  
                    InternetAddress[] to = new InternetAddress[tos.length];  
                    // 设置邮件消息的发送者  
                    for (int i = 0; i < tos.length; i++) {  
                        to[i] = new InternetAddress(tos[i]);  
                    }  
                    sendMailMessage.setRecipients(Message.RecipientType.TO, to);  
                }  
                  
                // 设置邮件抄送者地址  
                String[] toCCs = senderInfo.getToCarbonCopyAddress();  
                if(toCCs != null && toCCs.length != 0){  
                    InternetAddress[] toCC = new InternetAddress[toCCs.length];  
                    // 设置邮件消息的发送者  
                    for (int i = 0; i < toCCs.length; i++) {  
                        toCC[i] = new InternetAddress(toCCs[i]);  
                    }  
                    sendMailMessage.addRecipients(Message.RecipientType.CC, toCC);  
                }  
                  
                // 设置邮件密送者地址  
                String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress();  
                if(toBCCs != null && toBCCs.length != 0){  
                    InternetAddress[] toBCC = new InternetAddress[toBCCs.length];  
                    for (int i = 0; i < toBCCs.length; i++) {  
                        toBCC[i] = new InternetAddress(toBCCs[i]);  
                    }  
                    sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC);  
                }  
                  
                // 设置邮件主题  
                sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B"));  
                // 设置邮件内容  
                //sendMailMessage.setText(senderInfo.getContent());  
                Multipart multipart = new MimeMultipart();  
                // 邮件文本内容  
                if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){  
                    BodyPart part = new MimeBodyPart();  
                    part.setContent(senderInfo.getContent(), "text/html;charset=utf-8");//设置邮件文本内容  
                    multipart.addBodyPart(part);  
                }  
                  
                // 附件  
                String attachFileNames[] = senderInfo.getAttachFileNames();  
                int leng = attachFileNames == null ? 0 : attachFileNames.length;  
                for (int i = 0; i < leng; i++) {  
                    BodyPart part = new MimeBodyPart();  
                    // 根据文件名获取数据源  
                    DataSource dataSource = new FileDataSource(attachFileNames[i]);  
                    DataHandler dataHandler = new DataHandler(dataSource);  
                    // 得到附件本身并至入BodyPart  
                    part.setDataHandler(dataHandler);  
                    // 得到文件名同样至入BodyPart  
                    part.setFileName(MimeUtility.encodeText(dataSource.getName()));  
                    multipart.addBodyPart(part);  
                }  
                  
                sendMailMessage.setContent(multipart);  
                // 设置邮件发送的时间  
                sendMailMessage.setSentDate(new Date());  
                // 发送邮件  
                //Transport.send(sendMailMessage);  
                Transport transport = sendMailSession.getTransport("smtp");  
                transport.connect(senderInfo.getUserName(), senderInfo.getPassword());  
                transport.send(sendMailMessage,sendMailMessage.getAllRecipients());  
                  
                // 关闭transport  
                transport.close();  
                  
                flag = true;  
            } catch (AddressException e) {  
                e.printStackTrace();  
            } catch (MessagingException e) {  
                e.printStackTrace();  
            } catch (UnsupportedEncodingException e) {  
                e.printStackTrace();  
            }  
              
            return flag;  
        }  
    }

    (4)MailSendTest.java

    import org.junit.Test;
    
    /**
     * 发送邮件测试
     */
    public class MailSendTest {
        @Test
        public void run() {
            MailSenderInfo mailInfo = new MailSenderInfo();  
            mailInfo.setMailServerHost("smtp.126.com");  
            mailInfo.setMailServerPort("25");  
            mailInfo.setValidate(true);  
            mailInfo.setUserName("mabiao008"); // 发送人的邮箱用户名
            mailInfo.setPassword("XXXX"); // 发送人的邮箱密码  
            mailInfo.setFromAddress("mabiao008@126.com");  
            String[] to = {"360227812@qq.com"}; // 接收者的邮箱地址
            mailInfo.setToAddress(to);  
    //        String[] toCC = {"**********@qq.com"};  
    //        mailInfo.setToCarbonCopyAddress(toCC);  
    //        String[] toBCC = {"*******@sina.com"};  
    //        mailInfo.setToBlindCarbonCopyAddress(toBCC);  
    //        mailInfo.setAttachFileNames(new String[]{"D:/201611151651020897178_A.jpeg"});  
            mailInfo.setSubject("发送HTML邮件");  
            String body = "<table width=\"80%\" border=\"1\" cellpadding=\"0\" cellspacing=\"0\" style=\"align:center;text-align:center\"><tr><td>你好</td><td>你好</td><td>你好</td></tr></table>";  
            mailInfo.setContent(body);  
            // 这个类主要来发送邮件  
            System.out.println(SimpleMailSender.sendHtmlMail(mailInfo));;//发送文体格式  
        }
    }
  • 相关阅读:
    计算与软件工程 作业一
    C语言程序设计数组实验实验报告
    C语言程序设计第五次实验报告
    C语言程序设计第四次实验报告
    C语言程序设计第三次实验报告
    C程序设计实验报告第二次实验
    关于证书如何完成身份验证(SSL证书)
    openflow流表项中有关ip掩码的匹配的问题(控制器为ryu)
    解决sublime安装插件被墙失败的方法
    区块链技术与应用(二)之比特币中的数据结构
  • 原文地址:https://www.cnblogs.com/mabiao008/p/6094026.html
Copyright © 2020-2023  润新知