Subversion Repositories SmartDukaan

Rev

Rev 36250 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
35956 amit 1
package com.spice.profitmandi.service.mail;
2
 
3
import com.spice.profitmandi.common.util.Utils;
4
import com.spice.profitmandi.dao.entity.mail.MailOutbox;
5
import com.spice.profitmandi.dao.entity.mail.MailOutboxAttachment;
6
import com.spice.profitmandi.dao.repository.mail.MailOutboxRepository;
7
import org.apache.logging.log4j.LogManager;
8
import org.apache.logging.log4j.Logger;
9
import org.springframework.beans.factory.annotation.Autowired;
10
import org.springframework.beans.factory.annotation.Qualifier;
35960 amit 11
import org.springframework.beans.factory.annotation.Value;
35956 amit 12
import org.springframework.core.io.ByteArrayResource;
13
import org.springframework.core.io.InputStreamSource;
14
import org.springframework.mail.javamail.JavaMailSender;
15
import org.springframework.mail.javamail.MimeMessageHelper;
16
import org.springframework.stereotype.Service;
17
import org.springframework.transaction.annotation.Propagation;
18
import org.springframework.transaction.annotation.Transactional;
19
 
20
import javax.mail.internet.InternetAddress;
21
import javax.mail.internet.MimeMessage;
22
import java.io.File;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.nio.file.Files;
26
import java.time.LocalDateTime;
27
import java.util.List;
28
 
29
@Service
30
public class MailOutboxService {
31
 
32
    private static final Logger LOGGER = LogManager.getLogger(MailOutboxService.class);
33
 
34
    public static final String SENDER_SENDGRID = "SENDGRID";
35
    public static final String SENDER_GOOGLE = "GOOGLE";
36245 amit 36
    public static final String SENDER_RELAY = "RELAY";
35956 amit 37
 
35960 amit 38
    @Value("${prod}")
39
    private boolean prod;
40
 
41
    /**
42
     * In dev/staging, mails are sent to this address instead of actual recipients.
43
     * Set to empty to throw an exception (forces developer to set their email).
44
     */
45
    @Value("${mail.outbox.dev.recipient:}")
46
    private String devRecipient;
47
 
35956 amit 48
    @Autowired
49
    private MailOutboxRepository mailOutboxRepository;
50
 
51
    @Autowired
52
    @Qualifier("googleMailSender")
53
    private JavaMailSender googleMailSender;
54
 
36245 amit 55
    @Autowired
56
    @Qualifier("gmailRelaySender")
57
    private JavaMailSender gmailRelaySender;
58
 
35956 amit 59
    // ---- Default sender (SendGrid) convenience methods ----
60
 
61
    public void queueMail(String[] emailTo, String[] cc, String subject, String body, String source) {
62
        queueMail(emailTo, cc, null, subject, body, false, source, SENDER_SENDGRID, (AttachmentData[]) null);
63
    }
64
 
65
    public void queueMail(String emailTo, String[] cc, String subject, String body, String source) {
66
        queueMail(new String[]{emailTo}, cc, null, subject, body, false, source, SENDER_SENDGRID, (AttachmentData[]) null);
67
    }
68
 
69
    public void queueMail(String[] emailTo, String[] cc, String subject, String body, boolean html, String source) {
70
        queueMail(emailTo, cc, null, subject, body, html, source, SENDER_SENDGRID, (AttachmentData[]) null);
71
    }
72
 
73
    public void queueMail(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source) {
74
        queueMail(emailTo, cc, bcc, subject, body, html, source, SENDER_SENDGRID, (AttachmentData[]) null);
75
    }
76
 
77
    public void queueMailWithAttachments(String[] emailTo, String[] cc, String subject, String body, String source, Utils.Attachment... attachments) {
78
        queueMailWithAttachments(emailTo, cc, null, subject, body, false, source, SENDER_SENDGRID, attachments);
79
    }
80
 
81
    public void queueMailWithAttachments(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source, Utils.Attachment... attachments) {
82
        queueMailWithAttachments(emailTo, cc, bcc, subject, body, html, source, SENDER_SENDGRID, attachments);
83
    }
84
 
85
    // ---- Google sender convenience methods ----
86
 
87
    public void queueMailViaGoogle(String[] emailTo, String[] cc, String subject, String body, String source) {
88
        queueMail(emailTo, cc, null, subject, body, false, source, SENDER_GOOGLE, (AttachmentData[]) null);
89
    }
90
 
91
    public void queueMailViaGoogle(String emailTo, String[] cc, String subject, String body, String source) {
92
        queueMail(new String[]{emailTo}, cc, null, subject, body, false, source, SENDER_GOOGLE, (AttachmentData[]) null);
93
    }
94
 
95
    public void queueMailViaGoogle(String[] emailTo, String[] cc, String subject, String body, boolean html, String source) {
96
        queueMail(emailTo, cc, null, subject, body, html, source, SENDER_GOOGLE, (AttachmentData[]) null);
97
    }
98
 
99
    public void queueMailViaGoogle(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source) {
100
        queueMail(emailTo, cc, bcc, subject, body, html, source, SENDER_GOOGLE, (AttachmentData[]) null);
101
    }
102
 
103
    public void queueMailWithAttachmentsViaGoogle(String[] emailTo, String[] cc, String subject, String body, String source, Utils.Attachment... attachments) {
104
        queueMailWithAttachments(emailTo, cc, null, subject, body, false, source, SENDER_GOOGLE, attachments);
105
    }
106
 
107
    public void queueMailWithAttachmentsViaGoogle(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source, Utils.Attachment... attachments) {
108
        queueMailWithAttachments(emailTo, cc, bcc, subject, body, html, source, SENDER_GOOGLE, attachments);
109
    }
110
 
36245 amit 111
    // ---- Google Workspace Relay sender convenience methods ----
112
 
113
    public void queueMailViaRelay(String[] emailTo, String[] cc, String subject, String body, String source) {
114
        queueMail(emailTo, cc, null, subject, body, false, source, SENDER_RELAY, (AttachmentData[]) null);
115
    }
116
 
117
    public void queueMailViaRelay(String emailTo, String[] cc, String subject, String body, String source) {
118
        queueMail(new String[]{emailTo}, cc, null, subject, body, false, source, SENDER_RELAY, (AttachmentData[]) null);
119
    }
120
 
121
    public void queueMailViaRelay(String[] emailTo, String[] cc, String subject, String body, boolean html, String source) {
122
        queueMail(emailTo, cc, null, subject, body, html, source, SENDER_RELAY, (AttachmentData[]) null);
123
    }
124
 
125
    public void queueMailViaRelay(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source) {
126
        queueMail(emailTo, cc, bcc, subject, body, html, source, SENDER_RELAY, (AttachmentData[]) null);
127
    }
128
 
129
    public void queueMailWithAttachmentsViaRelay(String[] emailTo, String[] cc, String subject, String body, String source, Utils.Attachment... attachments) {
130
        queueMailWithAttachments(emailTo, cc, null, subject, body, false, source, SENDER_RELAY, attachments);
131
    }
132
 
133
    public void queueMailWithAttachmentsViaRelay(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source, Utils.Attachment... attachments) {
134
        queueMailWithAttachments(emailTo, cc, bcc, subject, body, html, source, SENDER_RELAY, attachments);
135
    }
136
 
35956 amit 137
    // ---- Internal methods ----
138
 
139
    private void queueMailWithAttachments(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source, String senderType, Utils.Attachment... attachments) {
140
        AttachmentData[] attachmentDataArray = null;
141
        if (attachments != null && attachments.length > 0) {
142
            attachmentDataArray = new AttachmentData[attachments.length];
143
            for (int i = 0; i < attachments.length; i++) {
144
                try {
145
                    byte[] data = readInputStreamSource(attachments[i].getInputStreamSource());
146
                    attachmentDataArray[i] = new AttachmentData(attachments[i].getFileName(), data, null);
147
                } catch (IOException e) {
148
                    LOGGER.error("Failed to read attachment: {}", attachments[i].getFileName(), e);
149
                    attachmentDataArray[i] = new AttachmentData(attachments[i].getFileName(), new byte[0], null);
150
                }
151
            }
152
        }
153
        queueMail(emailTo, cc, bcc, subject, body, html, source, senderType, attachmentDataArray);
154
    }
155
 
156
    public void queueMailWithFiles(String[] emailTo, String[] cc, String[] bcc, String subject, String body, String source, File... files) {
157
        AttachmentData[] attachmentDataArray = null;
158
        if (files != null && files.length > 0) {
159
            attachmentDataArray = new AttachmentData[files.length];
160
            for (int i = 0; i < files.length; i++) {
161
                try {
162
                    byte[] data = Files.readAllBytes(files[i].toPath());
163
                    String contentType = Files.probeContentType(files[i].toPath());
164
                    attachmentDataArray[i] = new AttachmentData(files[i].getName(), data, contentType);
165
                } catch (IOException e) {
166
                    LOGGER.error("Failed to read file attachment: {}", files[i].getName(), e);
167
                    attachmentDataArray[i] = new AttachmentData(files[i].getName(), new byte[0], null);
168
                }
169
            }
170
        }
171
        queueMail(emailTo, cc, bcc, subject, body, false, source, SENDER_SENDGRID, attachmentDataArray);
172
    }
173
 
174
    /**
175
     * Core method: persists mail + attachments in current transaction, triggers async send after commit.
176
     */
177
    private void queueMail(String[] emailTo, String[] cc, String[] bcc, String subject, String body, boolean html, String source, String senderType, AttachmentData... attachments) {
178
        MailOutbox mail = new MailOutbox();
179
        mail.setEmailTo(String.join(",", emailTo));
180
        if (cc != null && cc.length > 0) {
181
            mail.setEmailCc(String.join(",", cc));
182
        }
183
        if (bcc != null && bcc.length > 0) {
184
            mail.setEmailBcc(String.join(",", bcc));
185
        }
186
        mail.setSubject(subject != null ? subject : "");
187
        mail.setBody(body != null ? body : "");
188
        mail.setHtml(html);
189
        mail.setStatus("PENDING");
190
        mail.setRetryCount(0);
191
        mail.setCreatedAt(LocalDateTime.now());
192
        mail.setSource(source);
193
        mail.setSenderType(senderType);
194
 
195
        mailOutboxRepository.persist(mail);
196
 
197
        if (attachments != null) {
198
            for (AttachmentData att : attachments) {
199
                if (att != null && att.data.length > 0) {
200
                    MailOutboxAttachment attachment = new MailOutboxAttachment();
201
                    attachment.setMailOutboxId(mail.getId());
202
                    attachment.setFileName(att.fileName);
203
                    attachment.setFileData(att.data);
204
                    attachment.setContentType(att.contentType);
205
                    mailOutboxRepository.persistAttachment(attachment);
206
                }
207
            }
208
        }
209
 
210
    }
211
 
212
    @Transactional(propagation = Propagation.REQUIRES_NEW)
213
    public void processPendingMails() {
214
        List<MailOutbox> pendingMails = mailOutboxRepository.selectPending();
215
        LOGGER.info("Processing {} pending mails", pendingMails.size());
216
        for (MailOutbox mail : pendingMails) {
217
            sendAndUpdateStatus(mail);
218
        }
219
    }
220
 
221
    @Transactional(propagation = Propagation.REQUIRES_NEW)
222
    public void cleanupOldMails(int daysOld) {
223
        mailOutboxRepository.deleteOldSentMails(daysOld);
224
    }
225
 
36250 amit 226
    @Transactional(propagation = Propagation.REQUIRES_NEW)
227
    public void cleanupOldMails(int daysOld, String senderType) {
228
        mailOutboxRepository.deleteOldSentMailsBySenderType(daysOld, senderType);
229
    }
230
 
35956 amit 231
    private void sendAndUpdateStatus(MailOutbox mail) {
232
        try {
233
            List<MailOutboxAttachment> attachments = mailOutboxRepository.selectAttachmentsByMailId(mail.getId());
234
            sendSmtp(mail, attachments);
235
            mail.setStatus("SENT");
236
            mail.setSentAt(LocalDateTime.now());
237
            mail.setErrorMessage(null);
238
        } catch (Exception e) {
239
            LOGGER.error("Failed to send mail id={}, subject={}", mail.getId(), mail.getSubject(), e);
240
            mail.setStatus("FAILED");
241
            mail.setRetryCount(mail.getRetryCount() + 1);
242
            String errorMsg = e.getMessage();
243
            if (errorMsg != null && errorMsg.length() > 1000) {
244
                errorMsg = errorMsg.substring(0, 1000);
245
            }
246
            mail.setErrorMessage(errorMsg);
247
        }
248
    }
249
 
250
    private void sendSmtp(MailOutbox mail, List<MailOutboxAttachment> attachments) throws Exception {
35960 amit 251
        if (!prod) {
252
            if (devRecipient == null || devRecipient.trim().isEmpty()) {
253
                throw new IllegalStateException("Non-prod environment: set mail.outbox.dev.recipient in properties to your email before sending mails");
254
            }
255
            LOGGER.info("Non-prod: redirecting mail [subject={}] from [{}] to dev recipient [{}]", mail.getSubject(), mail.getEmailTo(), devRecipient);
256
        }
257
 
35956 amit 258
        JavaMailSender sender = resolveSender(mail.getSenderType());
259
        MimeMessage message = sender.createMimeMessage();
260
        boolean hasAttachments = attachments != null && !attachments.isEmpty();
261
        MimeMessageHelper helper = new MimeMessageHelper(message, hasAttachments);
262
 
35960 amit 263
        if (prod) {
264
            helper.setTo(mail.getEmailTo().split(","));
265
            if (mail.getEmailCc() != null && !mail.getEmailCc().isEmpty()) {
266
                helper.setCc(mail.getEmailCc().split(","));
267
            }
268
            if (mail.getEmailBcc() != null && !mail.getEmailBcc().isEmpty()) {
269
                helper.setBcc(mail.getEmailBcc().split(","));
270
            }
271
        } else {
272
            helper.setTo(devRecipient.trim());
35956 amit 273
        }
274
        helper.setSubject(mail.getSubject());
275
        helper.setText(mail.getBody(), mail.isHtml());
276
 
277
        String fromEmail = SENDER_GOOGLE.equals(mail.getSenderType()) ? "sdtech@smartdukaan.com" : "noreply@smartdukaan.com";
278
        String fromName = "SmartDukaan Care";
279
        helper.setFrom(new InternetAddress(fromEmail, fromName));
280
 
281
        if (hasAttachments) {
282
            for (MailOutboxAttachment att : attachments) {
283
                helper.addAttachment(att.getFileName(), new ByteArrayResource(att.getFileData()));
284
            }
285
        }
286
 
287
        sender.send(message);
288
    }
289
 
290
    private JavaMailSender resolveSender(String senderType) {
291
        if (SENDER_GOOGLE.equals(senderType)) {
292
            return googleMailSender;
293
        }
36249 amit 294
        // SendGrid and Relay both route through Google Workspace Relay
295
        return gmailRelaySender;
35956 amit 296
    }
297
 
298
    private byte[] readInputStreamSource(InputStreamSource source) throws IOException {
299
        try (InputStream is = source.getInputStream()) {
300
            return readAllBytes(is);
301
        }
302
    }
303
 
304
    private byte[] readAllBytes(InputStream is) throws IOException {
305
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
306
        byte[] buffer = new byte[8192];
307
        int len;
308
        while ((len = is.read(buffer)) != -1) {
309
            baos.write(buffer, 0, len);
310
        }
311
        return baos.toByteArray();
312
    }
313
 
314
    public static class AttachmentData {
315
        final String fileName;
316
        final byte[] data;
317
        final String contentType;
318
 
319
        public AttachmentData(String fileName, byte[] data, String contentType) {
320
            this.fileName = fileName;
321
            this.data = data;
322
            this.contentType = contentType;
323
        }
324
    }
325
}