JavaMail: msg.setSubject() won't accept second argument (encoding) in version 1.4.7, throws compile time error

StackOverflow https://stackoverflow.com//questions/22065810

  •  23-12-2019
  •  | 
  •  

I have a Java SE 7 project that uses maven with dependency:

<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
   <version>1.4.7</version>
</dependency>

Recently I noticed problems with sending mails - subjects that contained some special chars (specific to Polish language) weren't properly displayed.

I found few questions on SO with solution: add second argument to your setSubject() method, like this:

Message msg = new MimeMessage(session);
String subject = "ĄŻĄŻŚśążćół";
msg.setSubject(subject, "utf-8");

Looks nice, but NetBeans warned me that there is no overloaded method for setSubject() that accept two arguments. I ignored that, thought that "it's just NetBeans, probably it's some kind of internal error", but I was wrong.

I ran mvn clean install exec:java from terminal, and I got:

error: method setSubject in class Message cannot be applied to given types;

What's wrong? Documentation says that this version (1.4.7) supports specifing encoding in subject, every answer I found relies on that...

有帮助吗?

解决方案

Note that setSubject(String subject, String charset) is added to the MimeMessage class. I.e. it is not part of the Message class.

So, changing:

Message msg = new MimeMessage(session);

to

MimeMessage msg = new MimeMessage(session);

should fix your issue.

其他提示

Two things:

  1. According to the API documentation online setSubjects only takes a String as parameter.
  2. There would be no point in passing an additional encoding, because you already have a String.

Specifying encoding makes sense when converting between bytes and Strings. E.g. this String constructor (quoted from Oracle's Java API documentation):

String(byte[] bytes, int offset, int length, Charset charset)

Constructs a new String by decoding the specified subarray of bytes using the specified charset.

Here you already deliver a String (with non-ascii charaters), so having an encoding specified makes no sense.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top