java mail 发送带有附件的邮件

//创建属性对象(key-value)
        Properties pro = new Properties(); 
        pro.put("mail.smtp.auth", "true"); //发送服务器需要身份认证
        pro.put("mail.host", "smtp.qq.com");//设置邮件服务器
        pro.put("mail.transport.protocol", "smtp");//发送邮件的协议
        pro.put("mail.smtp.port", "465");//端口号
        //qq邮箱需要ssl加密
        pro.put("mail.smtp.socketFactory.port","465");
        pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        
        //创建会话对象
        Session session = Session.getInstance(pro);
        //创建消息对象
        Message message = new MimeMessage(session);
        //设置邮件的标题
        message.setSubject("测试邮件标题2"); 
        
        
        
        
        
        
        //内容附件对象
        Multipart part = new MimeMultipart();
        
        //文本内容
        BodyPart txt = new MimeBodyPart();
        //设置内容,格式
        txt.setContent("测试邮件内容2 <a href='https://www.baidu.com/'>百度一下</a>", "text/html;charset=utf-8");
        //把文本内容添加到part中
        part.addBodyPart(txt);
        
        //附件
        BodyPart addpendix = new MimeBodyPart();
        //数据源
        DataSource ds = new FileDataSource("F:\\yujun\\jar\\mail-1.4.7.jar");
        //添加附件
        addpendix.setDataHandler(new DataHandler(ds));
        //设置附件的名称
        //addpendix.setFileName("mail-1.4.7.jar");
        addpendix.setFileName(MimeUtility.encodeText("邮件mail-1.4.7.jar")); //解决乱码
        //把附件添加到part中
        part.addBodyPart(addpendix);
        
        //把part添加到消息对象中
        message.setContent(part);
        
        
        
        //设置发送人
        message.setFrom(new InternetAddress("[email protected]"));
        //设置接收人
        message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
        //创建消息发送对象
        Transport tran = session.getTransport();
        //链接         发送人       授权码
        tran.connect("[email protected]","ushychpeqzkmdcdj");
        //发送消息
        tran.sendMessage(message, message.getAllRecipients());
        //关闭
        tran.close();
        System.out.println("邮箱发送完毕....");

猜你喜欢

转载自www.cnblogs.com/chyxOne/p/9686075.html