feat(backend): implement step 7 — EmailSenderService (multipart SMTP)
This commit is contained in:
@@ -0,0 +1,41 @@
|
|||||||
|
package com.condado.newsletter.service
|
||||||
|
|
||||||
|
import jakarta.mail.internet.InternetAddress
|
||||||
|
import jakarta.mail.internet.MimeMessage
|
||||||
|
import org.slf4j.LoggerFactory
|
||||||
|
import org.springframework.mail.javamail.JavaMailSender
|
||||||
|
import org.springframework.mail.javamail.MimeMessageHelper
|
||||||
|
import org.springframework.stereotype.Service
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends AI-generated emails via SMTP using Spring's [JavaMailSender].
|
||||||
|
* Each email is sent as multipart (text/plain + text/html).
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
class EmailSenderService(private val mailSender: JavaMailSender) {
|
||||||
|
|
||||||
|
private val log = LoggerFactory.getLogger(javaClass)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends an email from a virtual entity to all configured recipients.
|
||||||
|
*
|
||||||
|
* @param from Sender email address (the virtual entity's email).
|
||||||
|
* @param to List of recipient email addresses.
|
||||||
|
* @param subject Email subject line.
|
||||||
|
* @param body Email body (may be plain text or simple HTML).
|
||||||
|
*/
|
||||||
|
fun send(from: String, to: List<String>, subject: String, body: String) {
|
||||||
|
log.info("Sending email from='$from' to=$to subject='$subject'")
|
||||||
|
val message: MimeMessage = mailSender.createMimeMessage()
|
||||||
|
val helper = MimeMessageHelper(message, true, "UTF-8")
|
||||||
|
helper.setFrom(InternetAddress(from))
|
||||||
|
helper.setTo(to.toTypedArray())
|
||||||
|
helper.setSubject(subject)
|
||||||
|
// Send as both plain text and HTML for maximum compatibility
|
||||||
|
val plainText = body.replace(Regex("<[^>]+>"), "").trim()
|
||||||
|
val htmlBody = if (body.contains(Regex("<[a-zA-Z]"))) body else "<pre>$body</pre>"
|
||||||
|
helper.setText(plainText, htmlBody)
|
||||||
|
mailSender.send(message)
|
||||||
|
log.info("Email sent successfully from='$from' subject='$subject'")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user