[英]Java send email with Japanese character
我正在使用 java 发送电子邮件。 要求是以不同语言发送电子邮件,对于日语,我收到的电子邮件为“???????” 人物。
代码是这样的:
import java.io.IOException;
import static java.nio.charset.StandardCharsets.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import java.io.File;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
@Service
public class EmailService {
@Autowired(required=true)
private JavaMailSenderImpl javaMailSender;
void sendEmailhtml(String to, String sub, String body, String imageFile) throws MessagingException, IOException {
javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("smtp.test.com");
MimeMessage msg = javaMailSender.createMimeMessage();
msg.setHeader("Content-Type", "text/html; charset=UTF-8");
msg.setContent("Content-Type", "text/html; charset=UTF-8");
MimeMessageHelper helper = new MimeMessageHelper(msg, true);
helper.setTo(to);
byte[] bytes = sub.getBytes();
sub = new String(bytes, UTF_8);
helper.setSubject(sub);
byte[] bytesBody = body.getBytes();
body = new String(bytesBody, UTF_8);
helper.setText(body,true);
// add image file as inline image
if(imageFile!= null) {
FileSystemResource fileresource = new FileSystemResource(new File(imageFile));
helper.addInline("referral-email-image", fileresource);
}
helper.setFrom("test@invalidemail.com");
javaMailSender.send(msg);
}
}
我正在使用以下参数值调用 sendEmailhtml 函数。
body=<p style="align-content: center;"> <img alt="referral emai header" src="cid:referral-email-image"/> </p> <p>FirstNameさん, </p> <p>CandidateFName CandidateLastName さんの社員紹介プロセスが完了しました.CandidateFNameさんは候補者プロフィールを作成され、現在、採用担当者がレビューを実施中です。<b>CandidateFName</b> さんに連絡を差し上げ、当社の <b> <a alt="Careers Site" href="https://test.com/">キャリアサイト</a></b> へのリンクから他の求人にも応募可能であることもご案内しました。 </p> <p> <p> 今回の推薦について重ねて御礼申し上げます。今後、あなたから当人に連絡をしていただく必要はありません。選考プロセスを進めるかどうかについて、採用担当者より <b>CandidateFName</b>さんに直接連絡を取らせていただきます。
sub=あなたが紹介した候補者に関する最新情報
提供的任何帮助将不胜感激。
我认为您的问题在于byte[] bytes = sub.getBytes();
此行为您获取系统上默认的字符集中的字符串字节,该字符集中可能不是 UTF-8。 将其更改为byte[] bytes = sub.getBytes(StandardCharsets.UTF_8);
这将首先将 String 转换为 UTF-8,然后将表示您的 String 内容的字节数组返回为 UTF-8 编码,而不是编码为您的系统默认字符集。 那么当你用 line 读取你的字节时
body = new String(bytesBody, UTF_8);
你应该得到想要的结果。
这里还有一个工具,它对我诊断和调试棘手的编码问题有很大帮助。 有一个开源 java 库 MgntUtils(由我编写),它有一个实用程序,可以将字符串转换为 unicode 序列,反之亦然:
result = "Hello World";
result = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(result);
System.out.println(result);
result = StringUnicodeEncoderDecoder.decodeUnicodeSequenceToString(result);
System.out.println(result);
这段代码的输出是:
\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064
Hello World
该库可以在Maven Central或Github上找到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.