java 实现发送邮件(带中文附件名称)

  java 实现发送邮件(带中文附件名称)

代码如下:

 /**
     * 发送带附件的邮件
     *
     * @param session    发件人信息
     * @param from       发件人地址
     * @param subject    邮件标题
     * @param content    邮件内容
     * @param recipients 收件人地址
     */
    public static void sendFileMail(Session session, String from, String recipients, String subject, String content, List attachments) {

        MimeMessage message = new MimeMessage(session);
        try {
            System.getProperties().setProperty("mail.mime.splitlongparameters", "false");

            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            message.setFrom(new InternetAddress(from));
            // 邮件标题
            message.setSubject(subject);
            // 添加邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);

            message.setSentDate(new Date());
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to = new InternetAddress(recipients);
            // Message.RecipientType.TO属性表示接收者的类型为TO
            message.setRecipient(Message.RecipientType.TO, to);

            // 添加附件的内容
            if (attachments != null) {
                for (int i = 0; i < attachments.size(); i++) {
                    BodyPart attachmentBodyPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachments.get(i));
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    // MimeUtility.encodeWord可以避免文件名乱码
                    attachmentBodyPart.setFileName(MimeUtility.encodeText(attachments.get(i).getName()));
                    multipart.addBodyPart(attachmentBodyPart);
                }
            }

            // 发送完整消息
            message.setContent(multipart);

            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

测试类如下:

 public static void main(String[] args) {
        Properties prop = new Properties();
        prop.put("mail.transport.protocol", "smtp");
        prop.put("mail.smtp.host", "smtp.163.com");
        prop.put("mail.smtp.auth", "true");
        final String smtpPort = "465";
        prop.setProperty("mail.smtp.port", smtpPort);
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.socketFactory.port", smtpPort);
        Session session = getSession(prop, "[email protected]", "123");

        File affix1 = new File("/Users/wangdandan/testfile/db777d64853a2177309a2c0836511779.jpg");
        File affix2 = new File("/Users/wangdandan/testfile/c12365db0c065735f156666813aa274a.jpg");
        File affix3 = new File("/Users/wangdandan/testfile/c779fa41271c2e576d699b3bc1d15bfa.jpg");
        File affix4 = new File("/Users/wangdandan/testfile/bac216e222e7e0a12a83c1ac43a366ed.jpg");
        List tempList = new ArrayList();
        List attList = new ArrayList();
        tempList.add(affix1);
        tempList.add(affix2);
        tempList.add(affix3);
        tempList.add(affix4);
        String name = "王二小(13314568990)体检报告"; //新文件名字

        try {
            // 把附件名称复制成想要的格式 格式:姓名(手机号)体检报告.jpg
            for (int i = 0; i < tempList.size(); i++) {
                File file = tempList.get(i);
                String filename = file.getAbsolutePath();
                String copyFileName = filename.substring(filename.indexOf("/"), filename.lastIndexOf("/"));
                copyFileName = copyFileName + "/" + name + (i + 1) + filename.substring(filename.indexOf("."));
                FileUtil.copyFile(filename, copyFileName);
                File copyFile = new File(copyFileName);
                attList.add(copyFile);
            }

            // 发送邮件
            sendFileMail(session, "[email protected]", "[email protected]",
                    "XX集团-入职体检报告-王二小-13314568990", "王二小(13314568990)的近3个月体检报告详见附件!", attList);

            // 删除copy的文件
            for (int i = 0; i < attList.size(); i++) {
                File file = attList.get(i);
                FileUtil.deleteFile(file.getAbsolutePath());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

注意:中文附件名称有可能出现乱码,以下两行代码可以解决乱码问题。

System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
attachmentBodyPart.setFileName(MimeUtility.encodeText(attachments.get(i).getName()));

 

你可能感兴趣的:(邮件)