I am using the JakartaMail API in my Spring Boot application and I have already created a fetch profile and I am able to get the message content printed out on the command line. However, I need some help in retrieving the email content from the IMAP server and storing it into an array so my client can properly display it. Furthermore, I am only getting envelope items, i.e. from, to subject, etc., but my request are not working and my requests are always timed out.
I need help in understanding a flow to properly retrieve the email and the envelope content to then send back to the client.
Here is detail run down of the code I have thus far we will start with the email service that will fetch the email content:
@Async
public CompletableFuture<List<EmailResponseDto>> fetchEmails() {
List<EmailResponseDto> emailResponseDtoList = new ArrayList<>();
try {
Properties prop = new Properties();
prop.put("mail.store.protocol", "imaps");
prop.put("mail.imaps.host", "imap.gmail.com");
prop.put("mail.imaps.port", "993");
prop.put("mail.imaps.ssl.enable", "true");
prop.put("mail.imaps.ssl.protocols", "TLSv1.2");
prop.put("mail.imaps.ssl.trust", "*");
Session emailSession = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
Store store = emailSession.getStore("imaps");
store.connect("username", "password");
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
emailFolder.fetch(emailFolder.getMessages(), profile);
for (Message message : emailFolder.getMessages()) {
EmailResponseDto emailResponseDto = new EmailResponseDto();
emailResponseDto.setSubject(message.getSubject());
emailResponseDto.setFrom(message.getFrom()[0].toString());
emailResponseDto.setSentDate(message.getSentDate());
emailResponseDtoList.add(emailResponseDto);
}
emailFolder.close(false);
store.close();
} catch (MessagingException e) {
e.printStackTrace();
}
return CompletableFuture.completedFuture(emailResponseDtoList);
}
I am able to get a response back, but I get a 401 response, and my API client tells me “No Body returned for Response”
I am using an async function because I understand I will get a ton of emails. However, even if I limit the amount, I am not able to get a response back. I am wondering is my implementation or logic, correct? Should I instead be writing the email content to a file instead?
Kamrul Hassan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1