@@ -9,10 +9,16 @@ import kotlinx.coroutines.Job
99import kotlinx.coroutines.launch
1010import org.apache.commons.mail.DefaultAuthenticator
1111import org.apache.commons.mail.Email
12+ import org.apache.commons.mail.EmailConstants.UTF_8
1213import org.apache.commons.mail.HtmlEmail
13- import org.apache.commons.mail.EmailConstants.*
1414import org.slf4j.Logger
1515import org.slf4j.LoggerFactory
16+ import java.io.File
17+ import java.net.URL
18+ import javax.activation.DataSource
19+ import javax.activation.FileDataSource
20+ import javax.activation.URLDataSource
21+ import javax.mail.util.ByteArrayDataSource
1622
1723class Mail (private val coroutineScope : CoroutineScope ? , private val config : SMTPConfig ) {
1824
@@ -31,6 +37,7 @@ class Mail(private val coroutineScope: CoroutineScope?, private val config: SMTP
3137 var fromName: String = " "
3238 var fromEmail: String = " "
3339 var charset = UTF_8
40+ var attachments: List <Attachment > = emptyList()
3441 private var isHtml: Boolean = false
3542
3643 private fun prepareEmail (): Email {
@@ -64,14 +71,16 @@ class Mail(private val coroutineScope: CoroutineScope?, private val config: SMTP
6471 email.addTo(entry.key, entry.value)
6572 }
6673
67- email.setCharset(charset);
74+ email.setCharset(charset)
75+ attachments.forEach { attachment ->
76+ email.attach(attachment.dataSource, attachment.name, attachment.description)
77+ }
6878
6979 return email
7080 }
7181
7282 fun send () {
73- val email = prepareEmail()
74- email.send()
83+ prepareEmail().send()
7584 }
7685
7786 fun sendAsync (): Job {
@@ -84,11 +93,27 @@ class Mail(private val coroutineScope: CoroutineScope?, private val config: SMTP
8493 try {
8594 email.send()
8695 } catch (t: Throwable ) {
87- LOGGER .error(t.localizedMessage)
96+ LOGGER .error(t.localizedMessage, t )
8897 }
8998 }
9099 }
91100
101+ class Attachment (
102+ val dataSource : DataSource ,
103+ val name : String ,
104+ val description : String? = null
105+ ) {
106+ constructor (file: File , name: String , description: String? = null ) : this (
107+ FileDataSource (file), name, description
108+ )
109+
110+ constructor (url: URL , name: String , description: String? = null ) : this (URLDataSource (url), name, description)
111+
112+ constructor (data: ByteArray , name: String , description: String? = null , charset: String = UTF_8 ) : this (
113+ ByteArrayDataSource (data, " application/octet-stream;charset=$charset " ), name, description
114+ )
115+ }
116+
92117 private companion object {
93118 val LOGGER : Logger = LoggerFactory .getLogger(Mail ::class .java)
94119 }
0 commit comments