I try to send a confirmation email after user registration. I am using the JavaMail library for this purpose and the Java 8 Base64 class.
I encode user emails as follows:
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 :
private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";
And then decode it in the ConfirmRegistrationCommand like this:
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; }
And when I try to decode:
http://localhost:8080/project/controller?command=confirmRegistration&ID=[ B@6499375d
I get java.lang.IllegalArgumentException: Illegal base64 character 5b .
I tried using a basic encoder / decoder (rather than URLs) without success.
SOLVE:
The problem is this: on the line:
String confirmLink = "Complete your registration by clicking on following"+ "\n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
I call toString in an array of bytes, so I have to do the following:
String encodedEmail = new String(Base64.getEncoder().encode( user.getEmail().getBytes(StandardCharsets.UTF_8)));
Thanks to Jon Skeet and ByteHamster .