我正在尝试在用户注册后发送确认电子邮件。为此,我使用 JavaMail 库和 Java 8 Base64 util 类。
我按以下方式对用户电子邮件进行编码:
byte[] encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8));
Multipart multipart = new MimeMultipart();
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-type", "text/html; charset=UTF-8");
String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
MimeBodyPart link = new MimeBodyPart(headers,
confirmLink.getBytes("UTF-8"));
multipart.addBodyPart(link);
where confirmationURL
is:
private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";
然后在ConfirmRegistrationCommand中以这种方式解码:
String encryptedEmail = request.getParameter("ID");
String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8);
RepositoryFactory repositoryFactory = RepositoryFactory
.getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY);
UserRepository userRepository = repositoryFactory.getUserRepository();
User user = userRepository.find(decodedEmail);
if (user.getEmail().equals(decodedEmail)) {
user.setActiveStatus(true);
return Path.WELCOME_PAGE;
} else {
return Path.ERROR_PAGE;
}
当我尝试解码时:
http://localhost:8080/project/controller?command=confirmRegistration&ID=[B@6499375d
我越来越java.lang.IllegalArgumentException: Illegal base64 character 5b
.
我尝试使用基本的编码/解码器(不是 URL 的)但没有成功。
SOLVED:
问题是下一个:
String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
我正在对字节数组调用 toString,因此我应该执行以下操作:
String encodedEmail = new String(Base64.getEncoder().encode(
user.getEmail().getBytes(StandardCharsets.UTF_8)));
谢谢乔恩·斯基特 and 字节仓.