Sending mail in android without intents using SMTP

后端 未结 6 2257
有刺的猬
有刺的猬 2020-11-29 03:28

Hi I am developing an android app which will send mail on click of a button. Code worked at first but due to some reason its not working now. Could anyone please help me wit

6条回答
  •  粉色の甜心
    2020-11-29 04:16

    Here's the code in Kotlin.
    Make sure to enable less secure app access in Gmail. To use secure access you will need to use OAUTH 2.
    read more at: OAuth 2.0 Mechanism

        val username = "username"
        val password = "email@gmail.com"
        try {
            val props = Properties()
            props["mail.smtp.auth"] = "true"
            props["mail.smtp.starttls.enable"] = "true"
            props["mail.smtp.host"] = "smtp.gmail.com"
            props["mail.smtp.port"] = "587"
    
            val session = Session.getInstance(props, object : Authenticator() {
                override fun getPasswordAuthentication(): PasswordAuthentication? {
                    return PasswordAuthentication(username, password)
                }
            })
    
            val message = MimeMessage(session)
            message.setFrom(username)
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("email@gmail.com"))
            message.subject = "Automated Violation Detection Email";
            message.setText(
                "Your Text"
                        
            )
    
            Thread {
                Transport.send(message)
            }.start()
        } catch (e: Exception) {
            println("Error: $e")
            showToastLong("Oops! Something Went Wrong! Please Try Again")
        }
    

提交回复
热议问题