java发送邮件(带附件)

@Test
    public void fun2() throws MessagingException, IOException{
        /**
         * 1.得到session
         * */
        Properties props = new Properties();
        //设置服务器地址
        props.setProperty("mail.host", "smtp.163.com");
        //设置邮件服务器是否需要登陆认证
        props.setProperty("mail.smtp.auth", "true");
        //创建认证器
        Authenticator auth = new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("账号名","授权码"); 
            }
        };
        //获取Session对象
        Session session = Session.getInstance(props,auth);
        /*
         * 2.创建mimeMessage
         * */
        //创建邮件对象
        MimeMessage msg = new MimeMessage(session);
        //设置发件人
        msg.setFrom(new InternetAddress("[email protected]"));
        //设置收件人,类型to
        msg.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
        //设置收件人,类型抄送
        msg.addRecipient(RecipientType.CC, new InternetAddress("[email protected]"));
        //设置收件人,类型暗送
        msg.addRecipient(RecipientType.BCC, new InternetAddress("[email protected]"));
        msg.setSubject("邮件的主题");

        //可以装载多个主体部件,可以把它当成一一个集合
        MimeMultipart partList = new MimeMultipart();
        //把邮件的内容设置为多部件的集合对象
        msg.setContent(partList);

        //创建一个部件
        MimeBodyPart part1 = new MimeBodyPart();
        part1.setContent("又一封邮件","text/html;charset=utf-8");
        //把部件添加到集合中
        partList.addBodyPart(part1);

        //又创建一个部件
        MimeBodyPart part2 = new MimeBodyPart();
        //为部件指定附件
        part2.attachFile(new File("C:\\Users\\hengli\\Desktop\\Firefly-v0.0.9.apk"));
        //part2.setFileName("FileName");//此处填中文名会出现编码错误
        part2.setFileName(MimeUtility.encodeText("fileName"));
        partList.addBodyPart(part2);  


        Transport.send(msg);


    }
}

测试通过

你可能感兴趣的:(Java)