在java邮件附件的奇怪的欧洲标志

时间:2014-07-24 11:48:34

标签: java encoding utf-8 javamail

当我发送附件中的以下代码而不是EURO符号的邮件时,我会得到一些奇怪的字符,如“â,¬;”。我已经将消息的内容类型设置为UTF-8以及OutputStreamWriter。这可能是什么原因?

    public static void sendMail(String email, String password, String sendTo, String subject, String msg)
    {
      Properties props = new Properties();
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

      final String fEMail = email;
      final String fPassword = password;

      Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
      {
        protected PasswordAuthentication getPasswordAuthentication()
        {
          return new PasswordAuthentication(fEMail, fPassword);
        }
      });

      try
      {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to mail address"));
        message.setSubject(subject);
        message.setContent("Hi", "text/plain; charset=UTF-8");


        File file = File.createTempFile("test", ".csv");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8").newEncoder());
        PrintWriter writer = new PrintWriter(outputStreamWriter);
        writer.println("\u20ac;");
        writer.println("€");
        writer.flush();

        MimeMultipart rootMultipart = new MimeMultipart("mixed");
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setDisposition(Part.ATTACHMENT);
        bodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
        bodyPart.setFileName(file.getName());
        rootMultipart.addBodyPart(bodyPart);
        message.setContent(rootMultipart);

        Transport.send(message);

        writer.close();
        file.delete();
        System.out.println("Message sent successfully!");

      }
      catch (MessagingException e)
      {
        throw new RuntimeException(e);
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }

1 个答案:

答案 0 :(得分:0)

首先,修复所有这些common mistakes

第一个message.setContent调用什么都不做,因为它被第二个message.setContent调用覆盖了。要创建带附件的邮件,Multipart需要包含主邮件正文的正文部分和附件的其他正文部分。

删除第二个writer.println调用。

真正的问题很可能是,当您附加文件时,它会为数据选择错误的字符集。尝试将系统属性“mail.mime.charset”设置为“utf-8”。