I want to send an email using Spring Boot and its mail library. Here is how I implemented it: The byteArray is not null and not empty.
class Attachment(val fileName: String, val byteArray: ByteArray)
private val emailSender: JavaMailSender
[...]
private fun sendMessage(to: String, subject: String, text: String, attachments: List<Attachment>? = null) {
val message = emailSender.createMimeMessage()
val helper = MimeMessageHelper(message, true)
message.setContent(text, "text/html; charset=utf-8")
helper.setFrom(sender)
helper.setTo(to)
helper.setSubject(subject)
// add attachment
attachments?.forEach { attachment ->
helper.addAttachment(attachment.fileName, ByteArrayResource(attachment.byteArray))
}
try {
emailSender.send(message)
} catch (e: MailException) {
logger.warn("Email could not be sent: $to, reason: ${e.message}")
}
}
If you use the mail helper class from Spring, then you also need to specify the html content there.
private fun sendMessage(to: String, subject: String, text: String, attachments: List<Attachment>? = null) {
val message = emailSender.createMimeMessage()
val helper = MimeMessageHelper(message, true)
helper.setFrom(sender)
helper.setTo(to)
helper.setSubject(subject)
helper.setText(text, true)
// add attachment
attachments?.forEach { attachment ->
helper.addAttachment(attachment.fileName, ByteArrayResource(attachment.byteArray))
}
try {
emailSender.send(message)
} catch (e: MailException) {
logger.warn("Email could not be sent: $to, reason: ${e.message}")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.