我想使用Spring Boot及其邮件库发送电子邮件。这是我的实现方式:
byteArray不为null,也不为空。
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}")
}
}
最佳答案
如果使用Spring的mail helper类,则还需要在其中指定html内容。
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}")
}
}