androidkotlin

Send event-related emails in kotlin


I want to send email to user when some event occurs, I had searched on internet and I couldn't find how to do it. Can anyone show me right path.


Solution

  • I used Javamail library for sending email to user with the help of sendgrid.net email server.

    Then I just implemented at what event I wanted to send email to the users. Tips: Use latest version of Javamail and don't forget to turn on Internet Permission in Manifest file

       private fun sendMail(etEmail: EditText, etSubject: EditText, etMessage: EditText) {
    
    
    
            // Set up the mail server
            val host = "smtp.sendgrid.net"
            val props = Properties().apply {
                put("mail.smtp.auth", "true")
                put("mail.smtp.ssl.enable", "true")
                put("mail.smtp.host", host)
                put("mail.smtp.port", "465")
            }
    
            // Set up authentication
            val session = Session.getInstance(props, object : Authenticator() {
                override fun getPasswordAuthentication() =
                    PasswordAuthentication("apikey","yourpaswordxyzfromsendgridaccount")
            })
    
            try {
                // Create a default MimeMessage object
                val message = MimeMessage(session).apply {
                    setFrom(InternetAddress("abc@xyz"))
                    addRecipient(Message.RecipientType.TO, InternetAddress(etEmail.text.toString()))
                    subject = etSubject.text.toString()
                    setText(etMessage.text.toString())
                }
    
                // Send the message
                thread(start = true) {
                    Transport.send(message)
                    println("Email sent successfully.")
    
                    println("running from thread(): ${Thread.currentThread()}")
                }
                Toast.makeText(this,"Mail sent",Toast.LENGTH_LONG).show()
    
    
    
            } catch (e: MessagingException) {
                e.printStackTrace()
            }
    
    
    }