Обычно при запуске моих тестов объект электронной почты возвращается с прикрепленными вложениями, и с помощью указанных тестов я могу утверждать, что все прикреплено с правильными именами и информацией.
Первоначальную версию, в которой я жестко запрограммировал все, можно увидеть ниже:
Код: Выделить всё
private final InputStream firstAttachment = WelcomeEmail.class
.getResourceAsStream("/META-INF/resources/attachments/welcome/example1.pdf");
private final InputStream secondAttachment =
WelcomeEmail.class.getResourceAsStream("/META-INF/resources/attachments/welcome/example2.pdf");
private final InputStream thirdAttachment = WelcomeEmail.class
.getResourceAsStream("/META-INF/resources/attachments/welcome/example3.pdf");
private final InputStream fourthAttachment = WelcomeEmail.class.getResourceAsStream(
"/META-INF/resources/attachments/welcome/example4.pdf");
/**
* Builds an instance of an email based on a specific template.
*
* @param paymentIntent Payment Intent used to extract information for the email generation
* @param context The Context used to populate the email template
* @return Instance of the Email template populated.
*/
@Override
public MailTemplateInstance build(PaymentIntentAggregate paymentIntent,
CustomerEmailContext context) {
if (paymentIntent == null) {
log.warn("Couldn't send customer Welcome Email: Missing Payment Intent");
return null;
}
String customerEmail = context.getCustomerEmail();
Mail mail = new Mail().setTo(List.of(customerEmail))
.setSubject(SIGN_ENCRYPT_SUBJECT_PREFIX + getSubject());
try {
mail.addAttachment("Name1.pdf", firstAttachment.readAllBytes(), ".pdf");
mail.addAttachment("Name2.pdf", secondAttachment.readAllBytes(), ".pdf");
mail.addAttachment("Name3.pdf", thirdAttachment.readAllBytes(), ".pdf");
mail.addAttachment("Name4.pdf", fourthAttachment.readAllBytes(), ".pdf");
} catch (IOException e) {
throw new RuntimeException(e);
}
return mailTemplate.of(mail).data("mailId", generateEmailId());
}
Чтобы улучшить этот код, я разработал следующую рефакторинговую версию:
Код: Выделить всё
private static final String ATTACHMENTS_DIRECTORY = "/META-INF/resources/attachments/welcome/";
/**
* Builds an instance of an email based on a specific template.
*
* @param paymentIntent Payment Intent used to extract information for the email generation
* @param context The Context used to populate the email template
* @return Instance of the Email template populated.
*/
@Override
public MailTemplateInstance build(PaymentIntentAggregate paymentIntent,
CustomerEmailContext context) {
if (paymentIntent == null) {
log.warn("Couldn't send customer Welcome Email: Missing Payment Intent");
return null;
}
String customerEmail = context.getCustomerEmail();
Mail mail = new Mail().setTo(List.of(customerEmail)).setSubject(getSubject())
.setAttachments(AttachmentService.getAttachments(ATTACHMENTS_DIRECTORY));
return mailTemplate.of(mail).data("mailId", generateEmailId());
}
Код: Выделить всё
@Slf4j
@ApplicationScoped
public class AttachmentService {
/**
* Gets all the attachments from the given resource name (directory)
*
* @param resourceName The resource name which must always be a directory
*
* @return All the attachments retrieved from the given resource
*/
public static List getAttachments(String resourceName) {
return getAttachmentNames(resourceName).stream()
.map(attachmentName -> getAttachment(resourceName + attachmentName, attachmentName))
.toList();
}
private static Attachment getAttachment(String attachmentFQN, String attachmentName) {
try (InputStream attachment = AttachmentService.class.getResourceAsStream(attachmentFQN)) {
return new Attachment(attachmentName, attachment.readAllBytes(), ContentType.PDF);
} catch (IOException ioException) {
log.error("An issue occurred while attempting to read attachment {}", attachmentFQN,
ioException);
throw new RuntimeException(ioException);
}
}
/**
* Retrieves all attachment names from the given resource (directory).
*
* @param resourceName The directory path
*
* @return List of all attachment names in the given directory
*/
private static List getAttachmentNames(String resourceName) {
try (BufferedReader directoryContentReader = new BufferedReader(
new InputStreamReader(AttachmentService.class.getResourceAsStream(resourceName)))) {
return directoryContentReader.lines().toList();
} catch (IOException ioException) {
log.error("An issue occurred while attempting to read attachment names from path {}",
resourceName, ioException);
throw new RuntimeException(ioException);
}
}
}
Проблема в том, что при запуске этого кода из JAR вложения не вставляются в электронное письмо, и электронное письмо отправляется как есть, без них. Другими словами, при развертывании кода электронное письмо отправляется без вложений.
Ошибки не регистрируются, поэтому невозможно определить, возникает ли проблема и где она возникает.< /p>
Я попытался изменить путь к каталогу, в котором хранятся вложения, и это сразу же выдает ошибку, которая говорит мне, что проблема не в текущем пути к каталогу.У меня есть одно подозрение: возможно, я каким-то образом неправильно обращаюсь с входными потоками при их использовании для чтения содержимого вложений, но в то же время никаких исключений не создается, и я использую try с ресурсами, чтобы специально закрыть потоки. когда закончу их использовать.
Буду очень признателен за любую помощь, заранее с уважением!
Некоторая документация, с которой я обращался при разработке этого кода :
- Документация Quarkus Mailer;
- Справочник по Mailer;
- Шаблон Qute Механизм;
- ClassLoader getResourceAsStream; (Проконсультировался на многих других сайтах по этой теме)
Подробнее здесь: https://stackoverflow.com/questions/788 ... ding-email