All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.migangqui.spring.email.service.EmailServiceImpl.kt Maven / Gradle / Ivy

package com.github.migangqui.spring.email.service

import com.github.migangqui.spring.email.bean.Email
import com.github.migangqui.spring.email.bean.SendEmailResult
import mu.KotlinLogging
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.io.InputStreamResource
import org.springframework.mail.MailException
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.mail.javamail.MimeMessageHelper
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.AsyncResult
import org.springframework.stereotype.Service
import java.util.concurrent.Future
import javax.mail.MessagingException
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

@Service
internal class EmailServiceImpl(private val javaMailSender: JavaMailSender) : EmailService {

    private val log = KotlinLogging.logger {}

    override fun send(email: Email): SendEmailResult {
        log.info { "Sending email" }
        return try {
            val generatedMailMessage = generateMailMessage(email)
            javaMailSender.send(generatedMailMessage)
            log.info { "Email sent successfully" }
            SendEmailResult(status = 200)
        } catch (e: MessagingException) {
            log.warn("An error has ocurred sending email", e)
            SendEmailResult(status = 500, cause = e.message, exception = e)
        } catch (e: MailException) {
            log.warn("An error has ocurred sending email", e)
            SendEmailResult(status = 500, cause = e.message, exception = e)
        }
    }

    @Async
    override fun sendAsync(email: Email): Future {
        return AsyncResult(send(email))
    }

    /* Private methods */

    @Throws(MessagingException::class)
    private fun generateMailMessage(email: Email): MimeMessage {
        val helper = MimeMessageHelper(javaMailSender.createMimeMessage(), email.file != null)

        helper.setFrom(InternetAddress(email.from))
        helper.setTo(email.to)
        helper.setSubject(email.subject!!)
        helper.setText(email.body, true)

        if (email.file != null && email.filename != null) {
            helper.addAttachment(email.filename, InputStreamResource(email.file))
        }
        return helper.mimeMessage
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy