Sending an email from an android in Kotlin.

huangapple go评论77阅读模式
英文:

Sending an email from an android in Kotlin

问题

我的应用在打开包含此代码的页面时崩溃。

class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val button1: Button = findViewById(R.id.button1)
        button1.setOnClickListener {
            Toast.makeText(this, "Button 1 Clicked!", Toast.LENGTH_SHORT).show()
        }
        main(arrayOf("myEmail@gmail.com", "password1", "myEmail@gmail.com", "myEmail@gmail.com", "myEmail@gmail.com"))
    }

    // 其他代码...
}

尝试在Kotlin中创建一个能够发送电子邮件而不需要打开电子邮件应用程序的应用程序。以上是我的代码。每当我在应用程序中访问此页面时,它会崩溃。我不确定该怎么办,有任何想法吗?目标是实现自动发送电子邮件而无需用户交互。用户只需输入一次信息,然后点击“发送”,它将生成日期和时间等信息,然后根据先前输入的信息发送。

这是由Logcat提供的错误堆栈跟踪:

---------------------------- 启动进程(17141)以包com.example.myapplication为目标 ----------------------------
2023-06-12 14:46:20.090 17141-17141 ziparchive              com.example.myapplication            W  无法打开'/data/data/com.example.myapplication/code_cache/.overlay/base.apk/classes3.dm':没有该文件或目录
2023-06-12 14:46:20.098 17141-17141 ziparchive              com.example.myapplication            W  无法打开'/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.dm':没有该文件或目录
2023-06-12 14:46:20.102 17141-17141 ziparchive              com.example.myapplication            W  无法打开'/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.dm':没有该文件或目录
2023-06-12 14:46:20.586 17141-17141 nativeloader            com.example.myapplication            D  为其他apk /data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.apk 配置clns-6。target_sdk_version=33,uses_libraries=,library_path=/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/lib/x86_64,permitted_path=/data:/mnt/expand:/data/user/0/com.example.myapplication
2023-06-12 14:46:20.663 17141-17141 GraphicsEnvironment     com.example.myapplication            V  当前设置的值为:
2023-06-12 14:46:20.665 17141-17141 GraphicsEnvironment     com.example.myapplication            V    angle_gl_driver_selection_pkgs=[]
2023-06-12 14:46:20.666 17141-17141 GraphicsEnvironment     com.example.myapplication            V    angle_gl_driver_selection_values=[]
2023-06-12 14:46:20.668 17141-17141 GraphicsEnvironment     com.example.myapplication            V  ANGLE GameManagerService for com.example.myapplication: false
2023-06-12 14:46:20.670 17141-17141 GraphicsEnvironment     com.example.myapplication            V  com.example.myapplication is not listed in per-application setting
2023-06-12 14:46:20.671 17141-17141 GraphicsEnvironment     com.example.myapplication            V  Neither updatable production driver nor prerelease driver is supported.
2023-06-12 14:46:21.063 17141-17173 libEGL                  com.example.myapplication            D  加载/lib64/egl/libEGL_emulation.so
2023-06-12 14:46:21.076 17141-17173 libEGL                  com.example.myapplication            D  加载/lib64/egl/libGLESv1_CM_emulation.so
2023-06-12 14:46:21.115 17141-17173 libEGL                  com.example.myapplication            D  加载/lib64/egl/libGLESv2_emulation.so
2023-06-12 14:46:21.416 17141-17141 AppCompatDelegate       com.example.myapplication            D  检查AppLocalesMetadataHolderService的元数据:未找到服务
2023-06-12 14:46:21.821 17141-17141 e.myapplication         com.example.myapplication            W  访问隐藏方法Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z(不支持,反射,允许)
2023-06-12 14:46:21.826 17141-17141 e.myapplication         com.example.myapplication            W  访问隐藏方法Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V(不支持,反射,允许)
2023-06-12 14:46:22.230 17141-17141 Compatibil...geReporter com.example.myapplication            D  报告的Compat更改ID:210923482;UID 10184;状态:启用
2023-06-12 14:46:22.783 17141-17141 Compatibil...geReporter com.example.myapplication            D  报告的Compat更改ID:237531167;UID 10184;状态:已禁用
2023-06-12 14:46:22.787 17141-17141 OpenGLRenderer          com.example.myapplication            W  未知数据空间0
2023-06-12 14:46:22.916 17141-17171 OpenGLRenderer          com.example.myapplication            W  选择具有EGL_SWAP_BEHAVIOR_PRESERVED的配置失败,无法选择,重试...
2023-06-12 14:46:22.918 17141-17141 AutofillManager         com.example.myapplication            D  通知进入填充对话框的视图:1073741824
2023-06-12 14:

<details>
<summary>英文:</summary>

my app crashes whenever i open the page that contains this code 

```kotlin
class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val button1: Button = findViewById(R.id.button1)
        button1.setOnClickListener {
            Toast.makeText(this, &quot;Button 1 Clicked!&quot;, Toast.LENGTH_SHORT).show()}
        main(arrayOf(&quot;myEmail@gmail.com&quot;,&quot;password1&quot;,&quot;myEmail@gmail.com&quot;,&quot;myEmail@gmail.com&quot;, &quot;myEmail@gmail.com&quot;))
        
        }
    fun main(args: Array&lt;String&gt;) {
        val userName =  args[0]
        val password =  args[1]

        val emailFrom = args[2]
        val emailTo = args[3]
        val emailCC = args[4]

        val subject = &quot;SMTP Test&quot;
        val text = &quot;Hello Kotlin Mail&quot;

        val props = Properties()
        putIfMissing(props, &quot;mail.smtp.host&quot;, &quot;smtp.office365.com&quot;)
        putIfMissing(props, &quot;mail.smtp.port&quot;, &quot;587&quot;)
        putIfMissing(props, &quot;mail.smtp.auth&quot;, &quot;true&quot;)
        putIfMissing(props, &quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;)

        val session = Session.getDefaultInstance(props, object : javax.mail.Authenticator() {
            override fun getPasswordAuthentication(): PasswordAuthentication {
                return PasswordAuthentication(userName, password)
            }
        })

        session.debug = true

        try {
            val mimeMessage = MimeMessage(session)
            mimeMessage.setFrom(InternetAddress(emailFrom))
            mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo, false))
            mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(emailCC, false))
            mimeMessage.setText(text)
            mimeMessage.subject = subject
            mimeMessage.sentDate = Date()

            val smtpTransport = session.getTransport(&quot;smtp&quot;)
            smtpTransport.connect()
            smtpTransport.sendMessage(mimeMessage, mimeMessage.allRecipients)
            smtpTransport.close()
        } catch (messagingException: MessagingException) {
            messagingException.printStackTrace()
        }
    }

    private fun putIfMissing(props: Properties, key: String, value: String) {
        if (!props.containsKey(key)) {
            props[key] = value
        }
    }

}

Trying to make an app in kotlin that is able to send emails without opening an email app, above is my code. whenever i go to this page in the app it crashes, im not sure what to do, any ideas? the goal is to have automated emails send without user interaction, they will put in their information once and then after that all they have to do is hit send and it will generate information such as date and time and then it will send based on previously entered information.

this is the error stack trace provided by logcat:

 ---------------------------- PROCESS STARTED (17141) for package com.example.myapplication ----------------------------
2023-06-12 14:46:20.090 17141-17141 ziparchive              com.example.myapplication            W  Unable to open &#39;/data/data/com.example.myapplication/code_cache/.overlay/base.apk/classes3.dm&#39;: No such file or directory
2023-06-12 14:46:20.098 17141-17141 ziparchive              com.example.myapplication            W  Unable to open &#39;/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.dm&#39;: No such file or directory
2023-06-12 14:46:20.102 17141-17141 ziparchive              com.example.myapplication            W  Unable to open &#39;/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.dm&#39;: No such file or directory
2023-06-12 14:46:20.586 17141-17141 nativeloader            com.example.myapplication            D  Configuring clns-6 for other apk /data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.myapplication
2023-06-12 14:46:20.663 17141-17141 GraphicsEnvironment     com.example.myapplication            V  Currently set values for:
2023-06-12 14:46:20.665 17141-17141 GraphicsEnvironment     com.example.myapplication            V    angle_gl_driver_selection_pkgs=[]
2023-06-12 14:46:20.666 17141-17141 GraphicsEnvironment     com.example.myapplication            V    angle_gl_driver_selection_values=[]
2023-06-12 14:46:20.668 17141-17141 GraphicsEnvironment     com.example.myapplication            V  ANGLE GameManagerService for com.example.myapplication: false
2023-06-12 14:46:20.670 17141-17141 GraphicsEnvironment     com.example.myapplication            V  com.example.myapplication is not listed in per-application setting
2023-06-12 14:46:20.671 17141-17141 GraphicsEnvironment     com.example.myapplication            V  Neither updatable production driver nor prerelease driver is supported.
2023-06-12 14:46:21.063 17141-17173 libEGL                  com.example.myapplication            D  loaded /vendor/lib64/egl/libEGL_emulation.so
2023-06-12 14:46:21.076 17141-17173 libEGL                  com.example.myapplication            D  loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2023-06-12 14:46:21.115 17141-17173 libEGL                  com.example.myapplication            D  loaded /vendor/lib64/egl/libGLESv2_emulation.so
2023-06-12 14:46:21.416 17141-17141 AppCompatDelegate       com.example.myapplication            D  Checking for metadata for AppLocalesMetadataHolderService : Service not found
2023-06-12 14:46:21.821 17141-17141 e.myapplication         com.example.myapplication            W  Accessing hidden method Landroid/view/View;-&gt;computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
2023-06-12 14:46:21.826 17141-17141 e.myapplication         com.example.myapplication            W  Accessing hidden method Landroid/view/ViewGroup;-&gt;makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
2023-06-12 14:46:22.230 17141-17141 Compatibil...geReporter com.example.myapplication            D  Compat change id reported: 210923482; UID 10184; state: ENABLED
2023-06-12 14:46:22.783 17141-17141 Compatibil...geReporter com.example.myapplication            D  Compat change id reported: 237531167; UID 10184; state: DISABLED
2023-06-12 14:46:22.787 17141-17141 OpenGLRenderer          com.example.myapplication            W  Unknown dataspace 0
2023-06-12 14:46:22.916 17141-17171 OpenGLRenderer          com.example.myapplication            W  Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2023-06-12 14:46:22.918 17141-17141 AutofillManager         com.example.myapplication            D  notifyViewEnteredForFillDialog:1073741824
2023-06-12 14:46:22.921 17141-17171 OpenGLRenderer          com.example.myapplication            W  Failed to initialize 101010-2 format, error = EGL_SUCCESS
2023-06-12 14:46:22.924 17141-17141 AutofillManager         com.example.myapplication            D  Triggering pre-emptive request for fill dialog.
2023-06-12 14:46:22.949 17141-17141 AutofillManager         com.example.myapplication            D  notifyViewEnteredForFillDialog:1073741825
2023-06-12 14:46:23.559 17141-17171 Gralloc4                com.example.myapplication            I  mapper 4.x is not supported
2023-06-12 14:46:23.616 17141-17171 OpenGLRenderer          com.example.myapplication            E  Unable to match the desired swap behavior.
2023-06-12 14:46:23.846 17141-17141 Choreographer           com.example.myapplication            I  Skipped 61 frames!  The application may be doing too much work on its main thread.
2023-06-12 14:46:23.875 17141-17141 Compatibil...geReporter com.example.myapplication            D  Compat change id reported: 163400105; UID 10184; state: ENABLED
2023-06-12 14:46:23.877 17141-17177 OpenGLRenderer          com.example.myapplication            I  Davey! duration=1035ms; Flags=1, FrameTimelineVsyncId=126882, IntendedVsync=8948596577142, Vsync=8948596577142, InputEventId=0, HandleInputStart=8948603131000, AnimationStart=8948603283200, PerformTraversalsStart=8948603452900, DrawStart=8949415107000, FrameDeadline=8948613243808, FrameInterval=8948602987400, FrameStartTime=16666666, SyncQueued=8949456775900, SyncStart=8949458121900, IssueDrawCommandsStart=8949461528900, SwapBuffers=8949627627500, FrameCompleted=8949633292400, DequeueBufferDuration=193600, QueueBufferDuration=2014400, GpuCompleted=8949631385600, SwapBuffersCompleted=8949633292400, DisplayPresentTime=0, CommandSubmissionCompleted=8949627627500, 
2023-06-12 14:46:23.906 17141-17141 AssistStructure         com.example.myapplication            I  Flattened final assist data: 1820 bytes, containing 1 windows, 9 views
2023-06-12 14:46:25.461 17141-17171 EGL_emulation           com.example.myapplication            D  app_time_stats: avg=268.99ms min=26.57ms max=1325.92ms count=6
2023-06-12 14:46:26.087 17141-17141 System.out              com.example.myapplication            I  DEBUG: setDebug: JavaMail version 1.6.0
2023-06-12 14:46:26.350 17141-17141 System.out              com.example.myapplication            I  DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
2023-06-12 14:46:26.414 17141-17141 AndroidRuntime          com.example.myapplication            D  Shutting down VM
2023-06-12 14:46:26.430 17141-17141 AndroidRuntime          com.example.myapplication            E  FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 17141
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity2}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3782)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3922)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:139)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2443)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:205)
at android.os.Looper.loop(Looper.java:294)
at android.app.ActivityThread.main(ActivityThread.java:8176)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1675)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getByName(InetAddress.java:1106)
at javax.mail.URLName.getHostAddress(URLName.java:520)
at javax.mail.URLName.hashCode(URLName.java:496)
at java.util.Hashtable.get(Hashtable.java:383)
at javax.mail.Session.getPasswordAuthentication(Session.java:889)
at javax.mail.Service.connect(Service.java:349)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at com.example.myapplication.MainActivity2.main(MainActivity2.kt:87)
at com.example.myapplication.MainActivity2.onCreate(MainActivity2.kt:24)
at android.app.Activity.performCreate(Activity.java:8595)
at android.app.Activity.performCreate(Activity.java:8573)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1456)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3764)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3922)&#160;
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)&#160;
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:139)&#160;
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)&#160;
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2443)&#160;
at android.os.Handler.dispatchMessage(Handler.java:106)&#160;
at android.os.Looper.loopOnce(Looper.java:205)&#160;
at android.os.Looper.loop(Looper.java:294)&#160;
at android.app.ActivityThread.main(ActivityThread.java:8176)&#160;
at java.lang.reflect.Method.invoke(Native Method)&#160;
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552)&#160;
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971)&#160;
2023-06-12 14:46:26.487 17141-17171 EGL_emulation           com.example.myapplication            D  app_time_stats: avg=19.01ms min=7.05ms max=67.51ms count=32
2023-06-12 14:46:26.550 17141-17141 Process                 com.example.myapplication            I  Sending signal. PID: 17141 SIG: 9
---------------------------- PROCESS ENDED (17141) for package com.example.myapplication ----------------------------

答案1

得分: 1

以下是翻译好的部分:

从异常信息中可以看到:
>java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity2}: android.os.NetworkOnMainThreadException

基本上,你不能在主线程(UI 线程)上执行网络操作,这是为了防止应用出现ANR(应用程序无响应)的政策,如果应用在5秒内不响应用户交互,Android会关闭它!你应该在不同的线程中处理网络相关的操作,这会让用户体验更好(如果应用在按下按钮后突然停止一段时间会很奇怪)。

这个问题已经在许多帖子中讨论过,比如这个,但是:

要解决这个问题,你可以:

  1. 覆盖这个规则(不推荐,可能会导致崩溃)
  2. 使用一个 runnable 或将网络请求分离到一个使用 viewModelScope 的 viewModel 函数中

另外,请确保你的 AppManifest 包含以下内容:

&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;

英文:

Well, from the exception:
>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity2}: android.os.NetworkOnMainThreadException

Basically, you cannot do network operations on the main (UI) thread, this is a policy to prevent the apps from ANRs (Application Not Responding, android will close an application if it does not respond to user interaction within 5 seconds!), you should handle networking "stuff" in a different thread, which makes the user experience a lot better (it would be weird if the app just... stopped for some time after you press a button)

This problem has already been covered in many posts, like this one, but:

To fix your issue you could:

  1. override this rule (BAD WAY, might cause crashes)
  2. use a runnable or separate the network request to a viewModel function that uses the viewModelScope

Also, make sure your AppManifest contains:

&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;

huangapple
  • 本文由 发表于 2023年6月13日 02:38:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定