Send Email using Kotlin

How to: Send Email using Kotlin

SendEmailUsingKotlin

Sending email in Kotlin is not as complicated as you think. Just a small piece of code and you can send the email to your recipient from the application. Let me show you the example of how to send an email using Kotlin.

In this example, I will be using the Yahoo SMTP server. You may switch to another SMTP server that you wish to use but do remember to change the properties in the code below:
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
fun main(args: Array<String>) {
Transport.send(plainMail())
}
private fun plainMail(): MimeMessage {
val tos = arrayListOf("xxxx@yahoo.com", "yyyy@gmail.com") //Multiple recipients
val from = "zzzz@yahoo.com" //Sender email
val properties = System.getProperties()
with (properties) {
put("mail.smtp.host", "smtp.mail.yahoo.com") //Configure smtp host
put("mail.smtp.port", "587") //Configure port
put("mail.smtp.starttls.enable", "true") //Enable TLS
put("mail.smtp.auth", "true") //Enable authentication
}
val auth = object: Authenticator() {
override fun getPasswordAuthentication() =
PasswordAuthentication(from, "password") //Credentials of the sender email
}
val session = Session.getDefaultInstance(properties, auth)
val message = MimeMessage(session)
with (message) {
setFrom(InternetAddress(from))
for (to in tos) {
addRecipient(Message.RecipientType.TO, InternetAddress(to))
subject = "This is the long long long subject" //Email subject
setContent("<html><body><h1>This is the actual message</h1></body></html>", "text/html; charset=utf-8") //Sending html message, you may change to send text here.
}
}
return message
}
view raw .kt hosted with ❤ by GitHub

Share your feedback in the comment section if you think this is helpful.

0 comments:

Post a Comment