【问题标题】:How to send email directly from Android device in Kotlin?如何在 Kotlin 中直接从 Android 设备发送电子邮件?
【发布时间】:2023-02-26 02:56:12
【问题描述】:

我很好奇直接从 Android 设备发送电子邮件。我尝试使用 sendgrid 这样做,但我在 HTTP 库中遇到了冲突。我也尝试使用 Intent 来实现这一点,但是使用 Action SEND.TO 我无法检测用户是否真的发送了电子邮件(总是返回 false)。谁能给我一些建议?

提前致谢。

【问题讨论】:

  • 得到帮助后才应该表示感谢。

标签: android android-intent intentfilter


【解决方案1】:

要直接从 Android 设备发送电子邮件,您可以使用 JavaMail API。以下是如何在 Kotlin 中使用它的示例:

  1. 将 JavaMail API 依赖项添加到您的项目。您可以像这样将它添加到您的build.gradle 文件中:

    依赖关系{ 实施 'com.sun.mail:android-mail:1.6.1' 实施 'com.sun.mail:android-activation:1.6.1' }

  2. 创建一个新的AsyncTask 子类来发送电子邮件。这是一个例子:

    导入 android.os.AsyncTask 导入 java.security.Security 导入 java.util.* 导入 javax.mail.* 导入 javax.mail.internet.InternetAddress 导入 javax.mail.internet.MimeMessage

    class SendMailTask​​(private val email: String, private val subject: String, private val message: String) : AsyncTask<Void?, Void?, Void?>() {

     override fun doInBackground(vararg params: Void?): Void? {
         val props = Properties()
         props.setProperty("mail.transport.protocol", "smtp")
         props.setProperty("mail.host", "smtp.gmail.com")
         props.put("mail.smtp.auth", "true")
         props.put("mail.smtp.port", "465")
         props.put("mail.smtp.socketFactory.port", "465")
         props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
         props.put("mail.smtp.socketFactory.fallback", "false")
    
         val session = Session.getDefaultInstance(props, object : Authenticator() {
             override fun getPasswordAuthentication(): PasswordAuthentication {
                 return PasswordAuthentication("your_email@gmail.com", "your_email_password")
             }
         })
    
         try {
             val message = MimeMessage(session)
             message.setFrom(InternetAddress("your_email@gmail.com"))
             message.addRecipient(Message.RecipientType.TO, InternetAddress(email))
             message.subject = subject
             message.setText(message)
             Transport.send(message)
         } catch (e: MessagingException) {
             e.printStackTrace()
         }
    
         return null
     }
    

    }

    在此示例中,我们使用 Gmail SMTP 服务器发送电子邮件。您需要将 "your_email@gmail.com""your_email_password" 替换为您的实际电子邮件地址和密码。

    要发送电子邮件,您可以创建 SendMailTask 类的新实例并调用它的 execute() 方法。这是一个例子:

    val email = "recipient@example.com"
    val subject = "Test email"
    val message = "This is a test email"
    SendMailTask(email, subject, message).execute()
    

    请注意,直接从 Android 设备发送电子邮件可能不如使用 SendGrid 等第三方服务可靠,因为它依赖于设备的网络连接和电子邮件设置。此外,请务必处理发送电子邮件时可能发生的任何异常,例如MessagingException

【讨论】:

  • Note that with this method, we cannot detect if the user actually sent the email or not. 好吧,就是这个问题。怎么做。仍然没有回答。
  • 感谢您的努力,但这不是解决方案
猜你喜欢
  • 2018-10-19
  • 2014-10-26
  • 2011-09-10
  • 2011-04-13
  • 2015-03-13
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 2014-11-04
相关资源
最近更新 更多