-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManageEmail.java
More file actions
246 lines (214 loc) · 9.31 KB
/
Copy pathManageEmail.java
File metadata and controls
246 lines (214 loc) · 9.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package it.aboutbits.springboot.emailservice.lib.application;
import it.aboutbits.springboot.emailservice.lib.AttachmentDataSource;
import it.aboutbits.springboot.emailservice.lib.EmailDto;
import it.aboutbits.springboot.emailservice.lib.EmailState;
import it.aboutbits.springboot.emailservice.lib.exception.AttachmentException;
import it.aboutbits.springboot.emailservice.lib.exception.EmailException;
import it.aboutbits.springboot.emailservice.lib.jpa.EmailRepository;
import it.aboutbits.springboot.emailservice.lib.model.Email;
import it.aboutbits.springboot.emailservice.lib.model.EmailAttachment;
import it.aboutbits.springboot.emailservice.lib.model.EmailContent;
import jakarta.mail.MessagingException;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.validation.annotation.Validated;
import java.io.IOException;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Validated
@Slf4j
@NullMarked
public class ManageEmail {
private final EmailRepository emailRepository;
private final JavaMailSender mailSender;
private final AttachmentDataSource attachmentDataSource;
private final EmailMapper emailMapper;
private final int maxAttempts;
private final Duration schedulerInterval;
private final TransactionTemplate transactionTemplate;
public ManageEmail(
EmailRepository emailRepository,
JavaMailSender mailSender,
AttachmentDataSource attachmentDataSource,
EmailMapper emailMapper,
int maxAttempts,
Duration schedulerInterval,
PlatformTransactionManager transactionManager
) {
this.emailRepository = emailRepository;
this.mailSender = mailSender;
this.attachmentDataSource = attachmentDataSource;
this.emailMapper = emailMapper;
this.maxAttempts = maxAttempts;
this.schedulerInterval = schedulerInterval;
// Persist the final email state in its own, independent transaction for sendOrFail to never make it roll back
this.transactionTemplate = new TransactionTemplate(transactionManager);
this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
public EmailDto schedule(@Valid EmailParameter parameter) throws EmailException {
Email email;
try {
email = fromParameter(parameter);
} catch (AttachmentException e) {
throw new EmailException(e);
}
var savedEmail = emailRepository.save(email);
return emailMapper.toDto(savedEmail);
}
public EmailDto sendOrFail(@Valid EmailParameter parameter) throws EmailException {
Email email;
try {
email = fromParameter(parameter);
} catch (AttachmentException e) {
throw new EmailException(e);
}
email.setExecutionStartTime(OffsetDateTime.now());
email.incrementAttempts();
try {
sendMail(email);
email.setState(EmailState.SENT);
email.setExecutionEndTime(OffsetDateTime.now());
} catch (MessagingException | AttachmentException | IOException | RuntimeException e) {
log.error("Failed to send email: {}", email.getId(), e);
email.setState(EmailState.ERROR);
email.setExecutionEndTime(OffsetDateTime.now());
email.setErrorMessage(e.getMessage());
}
var savedEmail = transactionTemplate.execute(_ -> emailRepository.save(email));
if (savedEmail.getState() == EmailState.ERROR) {
throw new EmailException("Failed to send email [id=%s, providerMessage=%s]"
.formatted(savedEmail.getId(), savedEmail.getErrorMessage()));
}
return emailMapper.toDto(savedEmail);
}
// Atomically transitions the row from PENDING/stale-SENDING into SENDING
@Transactional
Optional<Email> tryClaimForSend(long id, OffsetDateTime staleSendingBefore) {
var claimed = emailRepository.claimForSend(id, OffsetDateTime.now(), staleSendingBefore);
return claimed == 0 ? Optional.empty() : emailRepository.findById(id);
}
// Actually try sending the claimed email
Email completeClaimedSend(Email email) {
try {
sendMail(email);
email.setState(EmailState.SENT);
email.setExecutionEndTime(OffsetDateTime.now());
email.setErrorMessage(null);
} catch (Exception e) {
email.setExecutionEndTime(OffsetDateTime.now());
email.setErrorMessage(e.getMessage());
if (email.getAttempts() >= maxAttempts) {
log.error("Failed to send email: {}", email.getId(), e);
email.setState(EmailState.ERROR);
} else {
log.warn("Failed to send email: {}; Will be tried again", email.getId(), e);
email.setState(EmailState.PENDING);
email.setScheduledAt(
OffsetDateTime.now()
.plus(schedulerInterval.multipliedBy((long) Math.pow(2, email.getAttempts())))
);
}
}
return transactionTemplate.execute(_ -> emailRepository.save(email));
}
void cleanupAttachments(final Email email) throws AttachmentException {
for (var attachment : email.getAttachments()) {
attachmentDataSource.releaseAttachment(attachment.getFileReference());
}
email.setAttachmentsCleaned(true);
emailRepository.save(email);
}
private void sendMail(Email email) throws MessagingException, IOException, AttachmentException {
var content = email.getContent();
sendMail(
content.fromAddress(),
content.fromName(),
content.replyToAddress(),
content.replyToName(),
content.recipients(),
content.subject(),
content.htmlBody(),
content.textBody(),
email.getAttachments()
);
}
@SuppressWarnings("checkstyle:ParameterNumber")
private void sendMail(
String fromAddress,
String fromName,
@Nullable
String replyToAddress,
@Nullable
String replyToName,
List<String> recipients,
String subject,
String htmlBody,
String plainTextBody,
Set<EmailAttachment> attachments
) throws MessagingException, IOException, AttachmentException {
var message = mailSender.createMimeMessage();
var helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(fromAddress, fromName);
helper.setTo(recipients.toArray(String[]::new));
helper.setSubject(subject);
if (replyToAddress != null) {
if (replyToName != null) {
helper.setReplyTo(replyToAddress, replyToName);
} else {
helper.setReplyTo(replyToAddress);
}
}
if (!htmlBody.isBlank()) {
helper.setText(plainTextBody, htmlBody);
} else {
helper.setText(plainTextBody);
}
for (var attachment : attachments) {
var payload = attachmentDataSource.getAttachmentPayload(attachment.getFileReference());
helper.addAttachment(attachment.getFileName(), new ByteArrayResource(payload.readAllBytes()));
payload.close();
}
mailSender.send(message);
}
private Email fromParameter(EmailParameter parameter) throws AttachmentException {
var emailData = parameter.email();
var email = new Email();
email.setState(EmailState.PENDING);
email.setScheduledAt(parameter.scheduledAt());
email.setContent(new EmailContent(
emailData.subject(),
emailData.fromAddress(),
emailData.fromName(),
emailData.replyToAddress(),
emailData.replyToName(),
emailData.recipients(),
emailData.textBody(),
emailData.htmlBody()
));
var attachments = new HashSet<EmailAttachment>();
for (var attachment : parameter.email().attachments()) {
var reference = attachmentDataSource.storeAttachmentPayload(attachment.payload());
var emailAttachment = new EmailAttachment();
emailAttachment.setEmail(email);
emailAttachment.setContentType(attachment.contentType());
emailAttachment.setFileName(attachment.fileName());
emailAttachment.setFileReference(reference);
attachments.add(emailAttachment);
}
email.setAttachments(attachments);
return email;
}
}