my app crashes whenever i open the page that contains this code
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"))
}
fun main(args: Array<String>) {
val userName = args[0]
val password = args[1]
val emailFrom = args[2]
val emailTo = args[3]
val emailCC = args[4]
val subject = "SMTP Test"
val text = "Hello Kotlin Mail"
val props = Properties()
putIfMissing(props, "mail.smtp.host", "smtp.office365.com")
putIfMissing(props, "mail.smtp.port", "587")
putIfMissing(props, "mail.smtp.auth", "true")
putIfMissing(props, "mail.smtp.starttls.enable", "true")
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("smtp")
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 '/data/data/com.example.myapplication/code_cache/.overlay/base.apk/classes3.dm': No such file or directory
2023-06-12 14:46:20.098 17141-17141 ziparchive com.example.myapplication W Unable to open '/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.dm': No such file or directory
2023-06-12 14:46:20.102 17141-17141 ziparchive com.example.myapplication W Unable to open '/data/app/~~ElgGTbi-0GuD4FTf5MgSLg==/com.example.myapplication-D5fAv_4aBc46ggVTmpQXYg==/base.dm': 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;->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;->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)
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)
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 ----------------------------
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:
Also, make sure your AppManifest contains:
<uses-permission android:name="android.permission.INTERNET"/>