[英]Spring: MimeMessageHelper encoding for attachments
在Spring中,有一个选项可以设置邮件的编码:
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
这非常适合电子邮件的主题和消息。
但是,如果有附件,则将使用JVM的默认编码并在电子邮件的附件部分的Content-Type中指定(即使在部署jar时在应用程序中和/或通过参数全局指定编码)。
是否有人设法告诉Spring对邮件附件使用特定的编码? 我知道有一种使用此结构的方法:
messageHelper.addAttachment(filename, new InputStreamSource() {
@Override
public InputStream getInputStream () throws IOException {
return file.getInputStream();
}
}, "text/plain; charset=UTF-8");
问题是现在我必须手动描述每种附件类型和编码。 如果没有其他方法,那么我想这是唯一的方法。
最后,这就是我解决的方法(不是最干净的方法,但是可以正常工作):
private String determineContentType(String fileName) {
String contentType;
if (fileName.contains(".txt")) {
contentType = "text/plain; charset=" + mailProperties.getEncoding();
}
else if (fileName.contains(".xls")) {
contentType = "application/vnd.ms-excel; charset=" + mailProperties.getEncoding();
}
else if (fileName.contains(".pdf")) {
contentType = "application/pdf; charset=" + mailProperties.getEncoding();
}
else if (fileName.contains(".doc")) {
contentType = "application/msword; charset=" + mailProperties.getEncoding();
}
else if (fileName.contains(".xml")) {
contentType = "text/xml; charset=" + mailProperties.getEncoding();
}
else if (fileName.contains(".zip")) {
contentType = "application/zip; charset=" + mailProperties.getEncoding();
}
else {
contentType = "text/plain; charset=" + mailProperties.getEncoding();
}
return contentType;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.