Modern Apps git

← Modern-Apps.git

email: add support for other providers

Commit
b42b39841dbcad33e994e3e00423a3f0e99274e4
Author
Vayun Mathur <[email protected]>
When
2026-05-29 21:09 UTC (6 months ago)
Parents
c364969

Diff

email/src/main/java/com/vayunmathur/email/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/EmailManager.ktindex f2f5386b1e..9f50e324a6 100644--- a/email/src/main/java/com/vayunmathur/email/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailManager.kt@@ -2,6 +2,7 @@ package com.vayunmathur.email  import android.content.Context import android.net.Uri+import com.vayunmathur.email.data.CredentialCrypto import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File@@ -14,6 +15,39 @@ import javax.mail.internet.* import javax.mail.search.* import java.util.* +/**+ * IMAP or SMTP server endpoint. [useSsl] controls implicit SSL/TLS on connect+ * (the `imaps` / `smtps` protocols on ports 993 / 465); `false` selects plain+ * `imap` / `smtp` with a STARTTLS upgrade (ports 143 / 587).+ */+data class ServerConfig(val host: String, val port: Int, val useSsl: Boolean) {+    val imapProtocol: String get() = if (useSsl) "imaps" else "imap"+    val smtpProtocol: String get() = if (useSsl) "smtps" else "smtp"+}++/** Convenience: produce the IMAP server config that this account fetches from. */+fun EmailAccount.imapServer(): ServerConfig = ServerConfig(imapHost, imapPort, imapUseSsl)++/** Convenience: produce the SMTP server config used when sending from this account. */+fun EmailAccount.smtpServer(): ServerConfig = ServerConfig(smtpHost, smtpPort, smtpUseSsl)++/**+ * Decrypt the stored credentials and produce an [EmailManager.AuthType]+ * appropriate for this account — OAuth bearer token for Gmail, app password+ * for everything else.+ */+fun EmailAccount.authType(): EmailManager.AuthType {+    return if (authType == "oauth2") {+        EmailManager.AuthType.OAuth2(accessToken)+    } else {+        val cipher = passwordEncrypted+            ?: error("Password account ${email} is missing passwordEncrypted")+        val iv = passwordIv+            ?: error("Password account ${email} is missing passwordIv")+        EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv))+    }+}+ class EmailManager {      sealed class AuthType {@@ -21,31 +55,54 @@ class EmailManager {         data class OAuth2(val accessToken: String) : AuthType()     } -    private fun getImapSession(auth: AuthType, host: String): Session {+    private fun getImapSession(auth: AuthType, server: ServerConfig): Session {         val properties = Properties()-        properties["mail.store.protocol"] = "imaps"-        properties["mail.imaps.host"] = host-        properties["mail.imaps.port"] = "993"-        properties["mail.imaps.ssl.enable"] = "true"-        properties["mail.imaps.fetchsize"] = "1048576"-        properties["mail.imaps.partialfetch"] = "true"--        if (auth is AuthType.OAuth2) {-            properties["mail.imaps.auth.mechanisms"] = "XOAUTH2"+        if (server.useSsl) {+            properties["mail.store.protocol"] = "imaps"+            properties["mail.imaps.host"] = server.host+            properties["mail.imaps.port"] = server.port.toString()+            properties["mail.imaps.ssl.enable"] = "true"+            properties["mail.imaps.fetchsize"] = "1048576"+            properties["mail.imaps.partialfetch"] = "true"+            if (auth is AuthType.OAuth2) {+                properties["mail.imaps.auth.mechanisms"] = "XOAUTH2"+            }+        } else {+            properties["mail.store.protocol"] = "imap"+            properties["mail.imap.host"] = server.host+            properties["mail.imap.port"] = server.port.toString()+            properties["mail.imap.starttls.enable"] = "true"+            properties["mail.imap.starttls.required"] = "true"+            properties["mail.imap.fetchsize"] = "1048576"+            properties["mail.imap.partialfetch"] = "true"+            if (auth is AuthType.OAuth2) {+                properties["mail.imap.auth.mechanisms"] = "XOAUTH2"+            }         }         return Session.getInstance(properties).also { registerProviders(it) }     } -    private fun getSmtpSession(auth: AuthType, host: String): Session {+    private fun getSmtpSession(auth: AuthType, server: ServerConfig): Session {         val properties = Properties()-        properties["mail.transport.protocol"] = "smtps"-        properties["mail.smtps.host"] = host-        properties["mail.smtps.port"] = "465"-        properties["mail.smtps.ssl.enable"] = "true"-        properties["mail.smtps.auth"] = "true"--        if (auth is AuthType.OAuth2) {-            properties["mail.smtps.auth.mechanisms"] = "XOAUTH2"+        if (server.useSsl) {+            properties["mail.transport.protocol"] = "smtps"+            properties["mail.smtps.host"] = server.host+            properties["mail.smtps.port"] = server.port.toString()+            properties["mail.smtps.ssl.enable"] = "true"+            properties["mail.smtps.auth"] = "true"+            if (auth is AuthType.OAuth2) {+                properties["mail.smtps.auth.mechanisms"] = "XOAUTH2"+            }+        } else {+            properties["mail.transport.protocol"] = "smtp"+            properties["mail.smtp.host"] = server.host+            properties["mail.smtp.port"] = server.port.toString()+            properties["mail.smtp.starttls.enable"] = "true"+            properties["mail.smtp.starttls.required"] = "true"+            properties["mail.smtp.auth"] = "true"+            if (auth is AuthType.OAuth2) {+                properties["mail.smtp.auth.mechanisms"] = "XOAUTH2"+            }         }         return Session.getInstance(properties).also { registerProviders(it) }     }@@ -72,14 +129,15 @@ class EmailManager {         }     } -    suspend fun <T> withStore(host: String, user: String, auth: AuthType, block: suspend (Store) -> T): T = withContext(Dispatchers.IO) {-        val session = getImapSession(auth, host)-        val store = session.getStore("imaps")+    suspend fun <T> withStore(server: ServerConfig, user: String, auth: AuthType, block: suspend (Store) -> T): T = withContext(Dispatchers.IO) {+        val session = getImapSession(auth, server)+        val store = session.getStore(server.imapProtocol)         try {-            when (auth) {-                is AuthType.Password -> store.connect(host, user, auth.value)-                is AuthType.OAuth2 -> store.connect(host, user, auth.accessToken)+            val credential = when (auth) {+                is AuthType.Password -> auth.value+                is AuthType.OAuth2 -> auth.accessToken             }+            store.connect(server.host, server.port, user, credential)             block(store)         } finally {             store.close()@@ -216,12 +274,12 @@ class EmailManager {      * MessageThread screen the first time a message without a stored body is opened.      */     suspend fun fetchMessageBody(-        host: String,+        server: ServerConfig,         user: String,         auth: AuthType,         folderName: String,         uid: Long,-    ): Triple<String?, Boolean, List<Attachment>> = withStore(host, user, auth) { store ->+    ): Triple<String?, Boolean, List<Attachment>> = withStore(server, user, auth) { store ->         fetchMessageBodyInStore(store, user, folderName, uid)     } @@ -246,7 +304,7 @@ class EmailManager {         }     } -    suspend fun fetchFolders(host: String, user: String, auth: AuthType): List<EmailFolder> = withStore(host, user, auth) { store ->+    suspend fun fetchFolders(server: ServerConfig, user: String, auth: AuthType): List<EmailFolder> = withStore(server, user, auth) { store ->         val folders = store.defaultFolder.list("*")         folders.map { folder ->             EmailFolder(@@ -261,7 +319,7 @@ class EmailManager {     }      suspend fun fetchMessages(-        host: String,+        server: ServerConfig,         user: String,         auth: AuthType,         folderName: String,@@ -274,7 +332,7 @@ class EmailManager {          * returned for them. Saves a lot of network on repeated syncs.          */         skipUids: Set<Long> = emptySet(),-    ): Pair<List<EmailMessage>, List<Attachment>> = withStore(host, user, auth) { store ->+    ): Pair<List<EmailMessage>, List<Attachment>> = withStore(server, user, auth) { store ->         val folder = store.getFolder(folderName)         if ((folder.type and Folder.HOLDS_MESSAGES) == 0) return@withStore emptyList<EmailMessage>() to emptyList() @@ -363,7 +421,7 @@ class EmailManager {      suspend fun sendMessage(         context: Context,-        host: String,+        server: ServerConfig,         user: String,         auth: AuthType,         to: String,@@ -374,7 +432,7 @@ class EmailManager {         inReplyTo: String? = null,         references: String? = null     ) = withContext(Dispatchers.IO) {-        val session = getSmtpSession(auth, host)+        val session = getSmtpSession(auth, server)         val message = MimeMessage(session)         message.setFrom(InternetAddress(user))         message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))@@ -414,12 +472,13 @@ class EmailManager {          message.setContent(multipart) -        val transport = session.getTransport("smtps")+        val transport = session.getTransport(server.smtpProtocol)         try {-            when (auth) {-                is AuthType.Password -> transport.connect(host, user, auth.value)-                is AuthType.OAuth2 -> transport.connect(host, user, auth.accessToken)+            val credential = when (auth) {+                is AuthType.Password -> auth.value+                is AuthType.OAuth2 -> auth.accessToken             }+            transport.connect(server.host, server.port, user, credential)             transport.sendMessage(message, message.allRecipients)         } finally {             transport.close()@@ -441,14 +500,14 @@ class EmailManager {      suspend fun downloadAttachment(         context: Context,-        host: String,+        server: ServerConfig,         user: String,         auth: AuthType,         folderName: String,         uid: Long,         partId: String,         fileName: String-    ): String = withStore(host, user, auth) { store ->+    ): String = withStore(server, user, auth) { store ->         val folder = store.getFolder(folderName)         folder.open(Folder.READ_ONLY)         try {
email/src/main/java/com/vayunmathur/email/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/EmailModels.ktindex 359afd1f96..78d1eb8036 100644--- a/email/src/main/java/com/vayunmathur/email/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailModels.kt@@ -59,7 +59,28 @@ data class EmailAccount(     @PrimaryKey val email: String,     val accessToken: String,     val refreshToken: String? = null,-    val expiresAt: Long = 0+    val expiresAt: Long = 0,+    /**+     * Preset identifier — `gmail`, `outlook`, `yahoo`, `icloud`, `fastmail`, or+     * `custom`. Used to (a) skip Gmail-only behaviour (virtual folder filtering,+     * OAuth token refresh) for non-Gmail accounts, and (b) display the provider+     * name in account-picker UIs.+     */+    val provider: String = "gmail",+    /** IMAP hostname this account fetches from. Hard-coded to Gmail's pre-multi-provider migration. */+    val imapHost: String = "imap.gmail.com",+    val imapPort: Int = 993,+    /** true = implicit SSL/TLS on connect, false = plaintext + STARTTLS upgrade. */+    val imapUseSsl: Boolean = true,+    val smtpHost: String = "smtp.gmail.com",+    val smtpPort: Int = 465,+    val smtpUseSsl: Boolean = true,+    /** `oauth2` (Google) or `password` (app passwords / IMAP+SMTP). */+    val authType: String = "oauth2",+    /** AES-256-GCM ciphertext of the app password — null for OAuth2 accounts. */+    val passwordEncrypted: ByteArray? = null,+    /** GCM IV used to decrypt [passwordEncrypted]. */+    val passwordIv: ByteArray? = null, ) {     fun getColor(): Long {         val colors = listOf(
email/src/main/java/com/vayunmathur/email/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/EmailViewModel.ktindex 83594d6c6b..f59470bd10 100644--- a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt@@ -177,9 +177,9 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) {             suspend fun attemptSend(acct: EmailAccount) {                 emailManager.sendMessage(                     context = getApplication(),-                    host = "smtp.gmail.com",+                    server = acct.smtpServer(),                     user = acct.email,-                    auth = EmailManager.AuthType.OAuth2(acct.accessToken),+                    auth = acct.authType(),                     to = to,                     subject = subject,                     body = body,@@ -194,8 +194,11 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) {                 try {                     attemptSend(account)                 } catch (e: javax.mail.AuthenticationFailedException) {-                    // Token likely expired — refresh + retry once before-                    // giving up and saving to the outbox.+                    // For OAuth2 accounts the token might just be expired —+                    // refresh + retry once. Password accounts can't be+                    // auto-fixed, so just let the error fall through to the+                    // outbox-save path.+                    if (account.authType != "oauth2") throw e                     val refreshed = TokenRefresher.refresh(getApplication(), account)                         ?: throw e                     attemptSend(refreshed)@@ -238,12 +241,12 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) {     fun fetchBodyIfNeeded(message: EmailMessage) {         if (message.body != null) return         viewModelScope.launch {-            val account = dao.getAccounts().find { it.email == message.accountEmail } ?: return@launch+            val account = dao.getAccountByEmail(message.accountEmail) ?: return@launch             suspend fun attempt(acct: EmailAccount): Triple<String?, Boolean, List<Attachment>> {                 return emailManager.fetchMessageBody(-                    host = "imap.gmail.com",+                    server = acct.imapServer(),                     user = acct.email,-                    auth = EmailManager.AuthType.OAuth2(acct.accessToken),+                    auth = acct.authType(),                     folderName = message.folderName,                     uid = message.id,                 )@@ -252,6 +255,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) {                 val (body, isHtml, attachments) = try {                     attempt(account)                 } catch (e: javax.mail.AuthenticationFailedException) {+                    if (account.authType != "oauth2") throw e                     val refreshed = TokenRefresher.refresh(getApplication(), account) ?: throw e                     attempt(refreshed)                 }@@ -285,9 +289,9 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) {             try {                 val path = emailManager.downloadAttachment(                     context = getApplication(),-                    host = "imap.gmail.com",+                    server = account.imapServer(),                     user = account.email,-                    auth = EmailManager.AuthType.OAuth2(account.accessToken),+                    auth = account.authType(),                     folderName = attachment.folderName,                     uid = attachment.messageId,                     partId = attachment.partId,
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex e6eee6b8b1..9db3859576 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -81,12 +81,37 @@ class MainActivity : ComponentActivity() {             DynamicTheme {                 MainContent(                     viewModel = viewModel,-                    onGoogleLogin = { startGoogleLogin() }+                    onLaunchGoogleSignIn = { startGoogleLogin() }                 )             }         }     } +    /**+     * Public so the Compose [com.vayunmathur.email.ui.AddAccountScreen] can+     * trigger the Chrome-Custom-Tabs OAuth flow without owning the redirect+     * URI / PKCE state itself.+     */+    fun startGoogleLogin() {+        val verifier = generateCodeVerifier()+        TokenState.codeVerifier = verifier+        val challenge = generateCodeChallenge(verifier)++        val authUri = Uri.parse("https://accounts.google.com/o/oauth2/v2/auth")+            .buildUpon()+            .appendQueryParameter("client_id", clientId)+            .appendQueryParameter("redirect_uri", redirectUri)+            .appendQueryParameter("response_type", "code")+            .appendQueryParameter("scope", "https://mail.google.com/ email profile")+            .appendQueryParameter("code_challenge", challenge)+            .appendQueryParameter("code_challenge_method", "S256")+            .appendQueryParameter("access_type", "offline")+            .appendQueryParameter("prompt", "select_account")+            .build()++        startActivity(Intent(Intent.ACTION_VIEW, authUri))+    }+     override fun onStart() {         super.onStart()         com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground = true@@ -128,26 +153,6 @@ class MainActivity : ComponentActivity() {         }     } -    private fun startGoogleLogin() {-        val verifier = generateCodeVerifier()-        TokenState.codeVerifier = verifier-        val challenge = generateCodeChallenge(verifier)--        val authUri = Uri.parse("https://accounts.google.com/o/oauth2/v2/auth")-            .buildUpon()-            .appendQueryParameter("client_id", clientId)-            .appendQueryParameter("redirect_uri", redirectUri)-            .appendQueryParameter("response_type", "code")-            .appendQueryParameter("scope", "https://mail.google.com/ email profile")-            .appendQueryParameter("code_challenge", challenge)-            .appendQueryParameter("code_challenge_method", "S256")-            .appendQueryParameter("access_type", "offline")-            .appendQueryParameter("prompt", "select_account")-            .build()--        startActivity(Intent(Intent.ACTION_VIEW, authUri))-    }-     private fun exchangeCodeForToken(code: String) {         val verifier = TokenState.codeVerifier ?: return @@ -239,15 +244,23 @@ data class UserInfo( )  @Composable-fun MainContent(viewModel: EmailViewModel, onGoogleLogin: () -> Unit) {+fun MainContent(viewModel: EmailViewModel, onLaunchGoogleSignIn: () -> Unit) {     val accounts by viewModel.accounts.collectAsState(emptyList())     if (accounts.isEmpty()) {-        LoginScreen(onGoogleLogin)+        // First run: jump straight into the add-account picker. The conditional+        // above auto-swaps us into EmailApp once the first account lands.+        com.vayunmathur.email.ui.AddAccountScreen(+            onBack = null,+            onLaunchGoogleSignIn = onLaunchGoogleSignIn,+            onAccountAdded = {},+        )     } else {-        EmailApp(viewModel = viewModel, onAddAccount = onGoogleLogin)+        EmailApp(viewModel = viewModel, onLaunchGoogleSignIn = onLaunchGoogleSignIn)     } } +// Kept for backwards-compat if anything else references it; the active first-+// run UI is now AddAccountScreen. @OptIn(ExperimentalMaterial3Api::class) @Composable fun LoginScreen(onGoogleLogin: () -> Unit) {@@ -292,10 +305,12 @@ sealed interface Route : NavKey {     ) : Route     @Serializable     object Outbox : Route+    @Serializable+    object AddAccount : Route }  @Composable-fun EmailApp(viewModel: EmailViewModel, onAddAccount: () -> Unit) {+fun EmailApp(viewModel: EmailViewModel, onLaunchGoogleSignIn: () -> Unit) {     val scope = rememberCoroutineScope()     val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)     val context = LocalContext.current@@ -370,7 +385,7 @@ fun EmailApp(viewModel: EmailViewModel, onAddAccount: () -> Unit) {                             label = { Text("Add Account") },                             selected = false,                             onClick = {-                                onAddAccount()+                                backStack.add(Route.AddAccount)                                 scope.launch { drawerState.close() }                             },                             icon = { IconAdd() },@@ -462,6 +477,13 @@ fun EmailApp(viewModel: EmailViewModel, onAddAccount: () -> Unit) {                     onBack = { backStack.pop() }                 )             }+            entry<Route.AddAccount>(metadata = ListDetailPage()) {+                com.vayunmathur.email.ui.AddAccountScreen(+                    onBack = { backStack.pop() },+                    onLaunchGoogleSignIn = onLaunchGoogleSignIn,+                    onAccountAdded = { backStack.pop() },+                )+            }         }     } }
email/src/main/java/com/vayunmathur/email/data/CredentialCrypto.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/CredentialCrypto.kt b/email/src/main/java/com/vayunmathur/email/data/CredentialCrypto.ktnew file mode 100644index 0000000000..aa59e0546c--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/CredentialCrypto.kt@@ -0,0 +1,58 @@+package com.vayunmathur.email.data++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec++/**+ * AES-256-GCM encryption helper for [com.vayunmathur.email.EmailAccount.passwordEncrypted].+ *+ * The key lives in the Android Keystore (alias [KEY_ALIAS]) so it never leaves+ * the device and can't be exported even with root. Each encryption produces a+ * fresh 12-byte IV that we persist alongside the ciphertext in the+ * `passwordIv` column.+ */+object CredentialCrypto {++    private const val KEY_ALIAS = "email_account_pw"+    private const val ANDROID_KEYSTORE = "AndroidKeyStore"+    private const val TRANSFORMATION =+        KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE+    private const val GCM_TAG_BITS = 128++    /** Returns `(ciphertext, iv)`. The IV is randomly generated by the cipher. */+    fun encrypt(plain: String): Pair<ByteArray, ByteArray> {+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())+        val iv = cipher.iv+        val ciphertext = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))+        return ciphertext to iv+    }++    fun decrypt(ciphertext: ByteArray, iv: ByteArray): String {+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(GCM_TAG_BITS, iv))+        return String(cipher.doFinal(ciphertext), Charsets.UTF_8)+    }++    private fun getOrCreateKey(): SecretKey {+        val keystore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+        (keystore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }+        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)+        generator.init(+            KeyGenParameterSpec.Builder(+                KEY_ALIAS,+                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,+            )+                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+                .setKeySize(256)+                .build()+        )+        return generator.generateKey()+    }+}
email/src/main/java/com/vayunmathur/email/data/EmailDao.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDao.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDao.ktindex fe436b706b..a5d6b58e48 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDao.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDao.kt@@ -16,6 +16,9 @@ interface EmailDao {     @Query("SELECT * FROM EmailAccount")     suspend fun getAccounts(): List<EmailAccount> +    @Query("SELECT * FROM EmailAccount WHERE email = :email")+    suspend fun getAccountByEmail(email: String): EmailAccount?+     @Insert(onConflict = OnConflictStrategy.REPLACE)     suspend fun insertAccount(account: EmailAccount) 
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex 7be7e0a8dc..9e0d6fccda 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -20,7 +20,7 @@ import com.vayunmathur.email.OutboxEntry         Attachment::class,         OutboxEntry::class,     ],-    version = 6,+    version = 7,     exportSchema = false, ) abstract class EmailDatabase : RoomDatabase() {@@ -70,6 +70,28 @@ abstract class EmailDatabase : RoomDatabase() {             }         } +        /**+         * v6 → v7: Extend [EmailAccount] with per-account IMAP/SMTP server+         * config, a provider identifier, and an auth-type discriminator so we+         * can support providers beyond Gmail (Outlook, Yahoo, iCloud, Fastmail,+         * and arbitrary IMAP/SMTP servers). All defaults match the previous+         * hard-coded Gmail values so existing rows continue to sync.+         */+        private val MIGRATION_6_7 = object : Migration(6, 7) {+            override fun migrate(db: SupportSQLiteDatabase) {+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN provider TEXT NOT NULL DEFAULT 'gmail'")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN imapHost TEXT NOT NULL DEFAULT 'imap.gmail.com'")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN imapPort INTEGER NOT NULL DEFAULT 993")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN imapUseSsl INTEGER NOT NULL DEFAULT 1")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN smtpHost TEXT NOT NULL DEFAULT 'smtp.gmail.com'")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN smtpPort INTEGER NOT NULL DEFAULT 465")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN smtpUseSsl INTEGER NOT NULL DEFAULT 1")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN authType TEXT NOT NULL DEFAULT 'oauth2'")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN passwordEncrypted BLOB")+                db.execSQL("ALTER TABLE EmailAccount ADD COLUMN passwordIv BLOB")+            }+        }+         fun getInstance(context: Context): EmailDatabase {             return instance ?: synchronized(this) {                 instance ?: Room.databaseBuilder(@@ -77,7 +99,7 @@ abstract class EmailDatabase : RoomDatabase() {                     EmailDatabase::class.java,                     "email-db"                 )-                    .addMigrations(MIGRATION_4_5, MIGRATION_5_6)+                    .addMigrations(MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7)                     .build().also { instance = it }             }         }
email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.ktindex 8ba76176da..d7c9dbdee0 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -4,6 +4,8 @@ import android.content.Context import android.util.Log import androidx.work.* import com.vayunmathur.email.EmailManager+import com.vayunmathur.email.authType+import com.vayunmathur.email.imapServer import com.vayunmathur.email.widget.EmailWidget import androidx.glance.appwidget.updateAll import java.util.concurrent.TimeUnit@@ -32,13 +34,13 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :             var account = original             try {                 Log.d("EmailSync", ">>> Starting sync for account: ${account.email}")-                var auth = EmailManager.AuthType.OAuth2(account.accessToken)+                var auth = account.authType()                  // Open a SINGLE store for the whole account — folders + every                 // folder's message sync all reuse one TCP/TLS connection.                 // On auth failure we refresh the token and retry once.                 suspend fun runSync(authToUse: EmailManager.AuthType, accountToUse: com.vayunmathur.email.EmailAccount) {-                    manager.withStore("imap.gmail.com", accountToUse.email, authToUse) { store ->+                    manager.withStore(accountToUse.imapServer(), accountToUse.email, authToUse) { store ->                         Log.d("EmailSync", "Fetching folders for ${accountToUse.email}...")                         val folders = manager.fetchFoldersInStore(store, accountToUse.email)                         dao.insertFolders(folders)@@ -46,10 +48,13 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :                          // Folders we actually fetch messages from:                         //   - Must hold messages-                        //   - Skip Gmail's virtual folders that mirror INBOX (saves a huge-                        //     amount of duplicate downloads).+                        //   - For Gmail, skip the virtual labels that mirror INBOX+                        //     (saves a huge amount of duplicate downloads).+                        val skipSet = if (accountToUse.provider == com.vayunmathur.email.data.PROVIDER_GMAIL) {+                            GMAIL_VIRTUAL_FOLDERS+                        } else emptySet()                         val messageFolders = folders.filter { folder ->-                            folder.holdsMessages && folder.fullName !in GMAIL_VIRTUAL_FOLDERS+                            folder.holdsMessages && folder.fullName !in skipSet                         }                         val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1) @@ -148,6 +153,9 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :                 try {                     runSync(auth, account)                 } catch (e: javax.mail.AuthenticationFailedException) {+                    // Only OAuth2 accounts can be auto-recovered. Password+                    // accounts surface the auth error to the user instead.+                    if (account.authType != "oauth2") throw e                     Log.d("EmailSync", "Auth failed for ${account.email}; refreshing token")                     val refreshed = TokenRefresher.refresh(applicationContext, account)                         ?: throw e
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex cf6facb7d5..d7970fd749 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -15,6 +15,8 @@ import androidx.glance.appwidget.updateAll import com.sun.mail.imap.IMAPFolder import com.vayunmathur.email.EmailManager import com.vayunmathur.email.R+import com.vayunmathur.email.authType+import com.vayunmathur.email.imapServer import javax.mail.Folder import javax.mail.event.MessageCountAdapter import javax.mail.event.MessageCountEvent@@ -81,6 +83,10 @@ class ImapIdleService : Service() {                 backoffMs = 2_000L                 delay(1_000L)             } catch (e: javax.mail.AuthenticationFailedException) {+                if (account.authType != "oauth2") {+                    Log.w(TAG, "IDLE auth failed for password account ${account.email}; stopping retries")+                    return+                }                 Log.d(TAG, "IDLE auth failed for ${account.email}; refreshing token")                 val refreshed = TokenRefresher.refresh(applicationContext, account)                 if (refreshed != null) {@@ -112,9 +118,9 @@ class ImapIdleService : Service() {         withContext(Dispatchers.IO) {             val mgr = EmailManager()             mgr.withStore(-                host = "imap.gmail.com",+                server = account.imapServer(),                 user = account.email,-                auth = EmailManager.AuthType.OAuth2(account.accessToken),+                auth = account.authType(),             ) { store ->                 val folder = store.getFolder("INBOX") as IMAPFolder                 folder.open(Folder.READ_ONLY)
email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt b/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.ktindex 66cff469c4..9eaf52d9a1 100644--- a/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt@@ -13,6 +13,8 @@ import androidx.work.WorkManager import androidx.work.WorkerParameters import com.vayunmathur.email.EmailManager import com.vayunmathur.email.OutboxEntry+import com.vayunmathur.email.authType+import com.vayunmathur.email.smtpServer import kotlinx.serialization.json.Json import java.io.File import java.util.concurrent.TimeUnit@@ -106,9 +108,9 @@ class OutboxSendWorker(         suspend fun attempt(acct: com.vayunmathur.email.EmailAccount): kotlin.Result<Unit> = runCatching {             manager.sendMessage(                 context = applicationContext,-                host = "smtp.gmail.com",+                server = acct.smtpServer(),                 user = acct.email,-                auth = EmailManager.AuthType.OAuth2(acct.accessToken),+                auth = acct.authType(),                 to = entry.to,                 subject = entry.subject,                 body = entry.body,@@ -126,6 +128,10 @@ class OutboxSendWorker(             return SendResult.Failure(formatError(firstErr), firstErr)         }         // Token likely expired — refresh and retry exactly once.+        // Password accounts can't be auto-refreshed; treat as a hard failure.+        if (account.authType != "oauth2") {+            return SendResult.Failure(formatError(firstErr), firstErr)+        }         Log.d(TAG, "Auth failure on send; refreshing token for ${account.email}")         val refreshed = TokenRefresher.refresh(applicationContext, account)             ?: return SendResult.Failure(
email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt b/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.ktnew file mode 100644index 0000000000..6ffe8731f6--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt@@ -0,0 +1,114 @@+package com.vayunmathur.email.data++import com.vayunmathur.email.ServerConfig++/**+ * Built-in email provider with pre-filled IMAP/SMTP server settings + a short+ * instruction list for users who need to create an app password.+ *+ * `gmail` is the only OAuth2 preset; the rest use app passwords (long random+ * strings the user generates in their provider's account-security settings).+ * `custom` is the escape hatch — host/port/security are entered manually.+ */+data class ProviderPreset(+    val id: String,+    val displayName: String,+    val imap: ServerConfig?,+    val smtp: ServerConfig?,+    val authType: String,+    /** Link to the provider's help page on creating an app password. */+    val appPasswordHelpUrl: String?,+    /** Short bullet-point steps shown above the help link. */+    val instructions: List<String>,+)++const val PROVIDER_GMAIL = "gmail"+const val PROVIDER_OUTLOOK = "outlook"+const val PROVIDER_YAHOO = "yahoo"+const val PROVIDER_ICLOUD = "icloud"+const val PROVIDER_FASTMAIL = "fastmail"+const val PROVIDER_CUSTOM = "custom"++val PROVIDER_PRESETS: List<ProviderPreset> = listOf(+    ProviderPreset(+        id = PROVIDER_GMAIL,+        displayName = "Gmail",+        imap = ServerConfig("imap.gmail.com", 993, useSsl = true),+        smtp = ServerConfig("smtp.gmail.com", 465, useSsl = true),+        authType = "oauth2",+        appPasswordHelpUrl = null,+        instructions = emptyList(),+    ),+    ProviderPreset(+        id = PROVIDER_OUTLOOK,+        displayName = "Outlook / Microsoft 365",+        imap = ServerConfig("outlook.office365.com", 993, useSsl = true),+        smtp = ServerConfig("smtp-mail.outlook.com", 587, useSsl = false),+        authType = "password",+        appPasswordHelpUrl = "https://support.microsoft.com/en-us/account-billing/manage-app-passwords-for-two-step-verification-d6dc8c6d-4bf7-4851-ad95-6d07799387e9",+        instructions = listOf(+            "Two-step verification must be enabled on your Microsoft account.",+            "Go to https://account.microsoft.com/security → Advanced security options.",+            "Under \"App passwords\", choose \"Create a new app password\".",+            "Copy the generated password and paste it below.",+        ),+    ),+    ProviderPreset(+        id = PROVIDER_YAHOO,+        displayName = "Yahoo Mail",+        imap = ServerConfig("imap.mail.yahoo.com", 993, useSsl = true),+        smtp = ServerConfig("smtp.mail.yahoo.com", 465, useSsl = true),+        authType = "password",+        appPasswordHelpUrl = "https://help.yahoo.com/kb/SLN15241.html",+        instructions = listOf(+            "Sign in to Yahoo and open Account Info → Account security.",+            "Choose \"Generate app password\" (or \"Manage app passwords\").",+            "Pick \"Other app\" and name it \"Email\".",+            "Copy the 16-character password Yahoo shows and paste it below.",+        ),+    ),+    ProviderPreset(+        id = PROVIDER_ICLOUD,+        displayName = "iCloud Mail",+        imap = ServerConfig("imap.mail.me.com", 993, useSsl = true),+        smtp = ServerConfig("smtp.mail.me.com", 587, useSsl = false),+        authType = "password",+        appPasswordHelpUrl = "https://support.apple.com/en-us/102654",+        instructions = listOf(+            "Two-factor authentication must be enabled on your Apple ID.",+            "Go to https://account.apple.com → Sign-in and Security → App-Specific Passwords.",+            "Tap \"Generate an app-specific password\" and name it \"Email\".",+            "Copy the password and paste it below.",+            "Use your full iCloud email address as the username.",+        ),+    ),+    ProviderPreset(+        id = PROVIDER_FASTMAIL,+        displayName = "Fastmail",+        imap = ServerConfig("imap.fastmail.com", 993, useSsl = true),+        smtp = ServerConfig("smtp.fastmail.com", 465, useSsl = true),+        authType = "password",+        appPasswordHelpUrl = "https://www.fastmail.help/hc/en-us/articles/1500000278342",+        instructions = listOf(+            "Sign in at https://www.fastmail.com and open Settings → Password & Security.",+            "Under \"App passwords\", click \"New app password\".",+            "Give it a name like \"Email\" and grant IMAP + SMTP access.",+            "Copy the password and paste it below.",+        ),+    ),+    ProviderPreset(+        id = PROVIDER_CUSTOM,+        displayName = "Other (IMAP / SMTP)",+        imap = null,+        smtp = null,+        authType = "password",+        appPasswordHelpUrl = null,+        instructions = listOf(+            "Enter the IMAP and SMTP server details from your email provider.",+            "Most providers list these on a \"Server settings\" or \"Mail client setup\" page.",+            "If your provider requires an app password instead of your regular password, generate one there first.",+        ),+    ),+)++fun providerPreset(id: String): ProviderPreset? = PROVIDER_PRESETS.firstOrNull { it.id == id }
email/src/main/java/com/vayunmathur/email/data/TokenRefresher.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/TokenRefresher.kt b/email/src/main/java/com/vayunmathur/email/data/TokenRefresher.ktindex 8c0471b531..3dab96be8f 100644--- a/email/src/main/java/com/vayunmathur/email/data/TokenRefresher.kt+++ b/email/src/main/java/com/vayunmathur/email/data/TokenRefresher.kt@@ -33,6 +33,10 @@ object TokenRefresher {      * `expiresAt`) or `null` if the refresh failed.      */     suspend fun refresh(context: Context, account: EmailAccount): EmailAccount? {+        if (account.authType != "oauth2") {+            Log.d("TokenRefresher", "Skipping refresh for non-OAuth2 account ${account.email}")+            return null+        }         val refreshToken = account.refreshToken         if (refreshToken.isNullOrBlank()) {             Log.w("TokenRefresher", "No refresh token for ${account.email} — re-login required")
email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.ktnew file mode 100644index 0000000000..a5521a5bde--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt@@ -0,0 +1,404 @@+package com.vayunmathur.email.ui++import android.content.Context+import android.content.Intent+import android.net.Uri+import android.widget.Toast+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.*+import androidx.compose.runtime.*+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.PasswordVisualTransformation+import androidx.compose.ui.unit.dp+import com.vayunmathur.email.EmailAccount+import com.vayunmathur.email.EmailManager+import com.vayunmathur.email.ServerConfig+import com.vayunmathur.email.data.CredentialCrypto+import com.vayunmathur.email.data.EmailDatabase+import com.vayunmathur.email.data.EmailSyncWorker+import com.vayunmathur.email.data.ImapIdleService+import com.vayunmathur.email.data.PROVIDER_CUSTOM+import com.vayunmathur.email.data.PROVIDER_GMAIL+import com.vayunmathur.email.data.PROVIDER_PRESETS+import com.vayunmathur.email.data.ProviderPreset+import com.vayunmathur.library.ui.IconNavigation+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Add-account flow: pick a preset (Gmail / Outlook / Yahoo / iCloud / Fastmail+ * / Custom) → either kick off the Google OAuth flow (Gmail) or collect an app+ * password (everything else). After a successful "Test connection" the account+ * is encrypted-and-persisted and a one-off sync is kicked off.+ *+ * @param onBack pop the screen. Null when the screen is the first-run gate+ *   (the parent re-renders to the inbox automatically once an account exists).+ * @param onLaunchGoogleSignIn delegates to [com.vayunmathur.email.MainActivity.startGoogleLogin].+ * @param onAccountAdded invoked after a non-Gmail account is saved.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun AddAccountScreen(+    onBack: (() -> Unit)?,+    onLaunchGoogleSignIn: () -> Unit,+    onAccountAdded: () -> Unit,+) {+    var selectedProviderId by rememberSaveable { mutableStateOf<String?>(null) }+    val selectedProvider = selectedProviderId?.let { id -> PROVIDER_PRESETS.firstOrNull { it.id == id } }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text(if (selectedProvider == null) "Add account" else selectedProvider.displayName) },+                navigationIcon = {+                    val backTarget: (() -> Unit)? = when {+                        selectedProvider != null -> ({ selectedProviderId = null })+                        else -> onBack+                    }+                    if (backTarget != null) {+                        IconNavigation(backTarget)+                    }+                },+            )+        },+    ) { padding ->+        Box(Modifier.padding(padding).fillMaxSize()) {+            if (selectedProvider == null) {+                ProviderPicker(onPick = { selectedProviderId = it.id })+            } else {+                ProviderForm(+                    preset = selectedProvider,+                    onLaunchGoogleSignIn = onLaunchGoogleSignIn,+                    onAccountAdded = onAccountAdded,+                )+            }+        }+    }+}++@Composable+private fun ProviderPicker(onPick: (ProviderPreset) -> Unit) {+    Column(+        Modifier+            .fillMaxSize()+            .verticalScroll(rememberScrollState())+            .padding(16.dp),+    ) {+        Text(+            "Choose your email provider",+            style = MaterialTheme.typography.titleLarge,+            modifier = Modifier.padding(bottom = 16.dp),+        )+        PROVIDER_PRESETS.forEach { preset ->+            ElevatedCard(+                onClick = { onPick(preset) },+                modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),+            ) {+                Column(Modifier.padding(16.dp)) {+                    Text(preset.displayName, style = MaterialTheme.typography.titleMedium)+                    Text(+                        when (preset.id) {+                            PROVIDER_GMAIL -> "Sign in with Google"+                            PROVIDER_CUSTOM -> "Enter IMAP/SMTP server details manually"+                            else -> "App password"+                        },+                        style = MaterialTheme.typography.bodyMedium,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+            }+        }+    }+}++@Composable+private fun ProviderForm(+    preset: ProviderPreset,+    onLaunchGoogleSignIn: () -> Unit,+    onAccountAdded: () -> Unit,+) {+    if (preset.id == PROVIDER_GMAIL) {+        GmailForm(onLaunchGoogleSignIn = onLaunchGoogleSignIn)+    } else {+        PasswordForm(preset = preset, onAccountAdded = onAccountAdded)+    }+}++@Composable+private fun GmailForm(onLaunchGoogleSignIn: () -> Unit) {+    Column(+        Modifier+            .fillMaxSize()+            .verticalScroll(rememberScrollState())+            .padding(16.dp),+        verticalArrangement = Arrangement.spacedBy(12.dp),+    ) {+        Text(+            "You'll be redirected to Google to sign in. New mail will start syncing automatically once you're back.",+            style = MaterialTheme.typography.bodyMedium,+        )+        Button(+            onClick = onLaunchGoogleSignIn,+            modifier = Modifier.fillMaxWidth(),+        ) {+            Text("Continue with Google")+        }+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun PasswordForm(+    preset: ProviderPreset,+    onAccountAdded: () -> Unit,+) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()++    var email by rememberSaveable { mutableStateOf("") }+    var password by rememberSaveable { mutableStateOf("") }+    var passwordVisible by rememberSaveable { mutableStateOf(false) }++    // Custom-provider-only fields. Pre-filled with sensible IMAP/SMTP defaults+    // (993/465 SSL) that work for the majority of mail hosts; advanced users+    // can flip to STARTTLS via the radio buttons.+    var imapHost by rememberSaveable { mutableStateOf(preset.imap?.host ?: "") }+    var imapPort by rememberSaveable { mutableStateOf((preset.imap?.port ?: 993).toString()) }+    var imapUseSsl by rememberSaveable { mutableStateOf(preset.imap?.useSsl ?: true) }+    var smtpHost by rememberSaveable { mutableStateOf(preset.smtp?.host ?: "") }+    var smtpPort by rememberSaveable { mutableStateOf((preset.smtp?.port ?: 465).toString()) }+    var smtpUseSsl by rememberSaveable { mutableStateOf(preset.smtp?.useSsl ?: true) }++    var working by remember { mutableStateOf(false) }+    var error by remember { mutableStateOf<String?>(null) }++    Column(+        Modifier+            .fillMaxSize()+            .verticalScroll(rememberScrollState())+            .padding(16.dp),+        verticalArrangement = Arrangement.spacedBy(12.dp),+    ) {+        if (preset.instructions.isNotEmpty()) {+            InstructionsCard(preset = preset)+        }++        OutlinedTextField(+            value = email,+            onValueChange = { email = it.trim() },+            label = { Text("Email address") },+            singleLine = true,+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),+            modifier = Modifier.fillMaxWidth(),+        )+        OutlinedTextField(+            value = password,+            onValueChange = { password = it },+            label = { Text(if (preset.id == PROVIDER_CUSTOM) "Password" else "App password") },+            singleLine = true,+            visualTransformation = if (passwordVisible) androidx.compose.ui.text.input.VisualTransformation.None+            else PasswordVisualTransformation(),+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),+            trailingIcon = {+                TextButton(onClick = { passwordVisible = !passwordVisible }) {+                    Text(if (passwordVisible) "Hide" else "Show")+                }+            },+            modifier = Modifier.fillMaxWidth(),+        )++        if (preset.id == PROVIDER_CUSTOM) {+            Text("IMAP (incoming)", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)+            ServerRow(+                host = imapHost, onHostChange = { imapHost = it.trim() },+                port = imapPort, onPortChange = { imapPort = it.filter(Char::isDigit) },+                useSsl = imapUseSsl, onSslChange = { imapUseSsl = it },+            )+            Text("SMTP (outgoing)", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)+            ServerRow(+                host = smtpHost, onHostChange = { smtpHost = it.trim() },+                port = smtpPort, onPortChange = { smtpPort = it.filter(Char::isDigit) },+                useSsl = smtpUseSsl, onSslChange = { smtpUseSsl = it },+            )+        }++        if (error != null) {+            Text(+                error!!,+                color = MaterialTheme.colorScheme.error,+                style = MaterialTheme.typography.bodySmall,+            )+        }++        Button(+            enabled = !working+                && email.isNotBlank() && password.isNotBlank()+                && (preset.id != PROVIDER_CUSTOM+                    || (imapHost.isNotBlank() && smtpHost.isNotBlank()+                        && imapPort.isNotBlank() && smtpPort.isNotBlank())),+            onClick = {+                error = null+                working = true+                scope.launch {+                    val imap = preset.imap+                        ?: ServerConfig(imapHost, imapPort.toIntOrNull() ?: 993, imapUseSsl)+                    val smtp = preset.smtp+                        ?: ServerConfig(smtpHost, smtpPort.toIntOrNull() ?: 465, smtpUseSsl)+                    val result = testAndPersistAccount(+                        context = context,+                        providerId = preset.id,+                        email = email,+                        password = password,+                        imap = imap,+                        smtp = smtp,+                    )+                    working = false+                    if (result == null) {+                        Toast.makeText(context, "Account added", Toast.LENGTH_SHORT).show()+                        onAccountAdded()+                    } else {+                        error = result+                    }+                }+            },+            modifier = Modifier.fillMaxWidth(),+        ) {+            if (working) {+                CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)+                Spacer(Modifier.width(8.dp))+                Text("Testing connection…")+            } else {+                Text("Test connection & save")+            }+        }+    }+}++@Composable+private fun InstructionsCard(preset: ProviderPreset) {+    val context = LocalContext.current+    ElevatedCard(modifier = Modifier.fillMaxWidth()) {+        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+            Text("How to get your app password", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)+            preset.instructions.forEachIndexed { i, line ->+                Text("${i + 1}. $line", style = MaterialTheme.typography.bodySmall)+            }+            preset.appPasswordHelpUrl?.let { url ->+                Spacer(Modifier.height(4.dp))+                TextButton(onClick = { openUrl(context, url) }) {+                    Text("Open ${preset.displayName} app-password help")+                }+            }+        }+    }+}++@Composable+private fun ServerRow(+    host: String, onHostChange: (String) -> Unit,+    port: String, onPortChange: (String) -> Unit,+    useSsl: Boolean, onSslChange: (Boolean) -> Unit,+) {+    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+        OutlinedTextField(+            value = host,+            onValueChange = onHostChange,+            label = { Text("Host") },+            singleLine = true,+            modifier = Modifier.weight(2f),+        )+        OutlinedTextField(+            value = port,+            onValueChange = onPortChange,+            label = { Text("Port") },+            singleLine = true,+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+            modifier = Modifier.weight(1f),+        )+    }+    Row(verticalAlignment = Alignment.CenterVertically) {+        Text("Security:", modifier = Modifier.padding(end = 8.dp))+        FilterChip(+            selected = useSsl,+            onClick = { onSslChange(true) },+            label = { Text("SSL/TLS") },+        )+        Spacer(Modifier.width(8.dp))+        FilterChip(+            selected = !useSsl,+            onClick = { onSslChange(false) },+            label = { Text("STARTTLS") },+        )+    }+}++private fun openUrl(context: Context, url: String) {+    runCatching {+        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {+            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        })+    }+}++/**+ * Try the supplied IMAP credentials by listing folders; on success encrypt the+ * password, persist the [EmailAccount], and start syncing. Returns `null` on+ * success or a human-readable error message on failure.+ */+private suspend fun testAndPersistAccount(+    context: Context,+    providerId: String,+    email: String,+    password: String,+    imap: ServerConfig,+    smtp: ServerConfig,+): String? = withContext(Dispatchers.IO) {+    try {+        EmailManager().fetchFolders(+            server = imap,+            user = email,+            auth = EmailManager.AuthType.Password(password),+        )+    } catch (e: javax.mail.AuthenticationFailedException) {+        return@withContext "Authentication failed — check your email and app password."+    } catch (e: Exception) {+        return@withContext "Couldn't reach ${imap.host}:${imap.port} — ${e.javaClass.simpleName}: ${e.message ?: "unknown error"}"+    }++    val (cipher, iv) = try {+        CredentialCrypto.encrypt(password)+    } catch (e: Exception) {+        return@withContext "Couldn't store password securely: ${e.message}"+    }++    val account = EmailAccount(+        email = email,+        accessToken = "",+        refreshToken = null,+        expiresAt = 0,+        provider = providerId,+        imapHost = imap.host,+        imapPort = imap.port,+        imapUseSsl = imap.useSsl,+        smtpHost = smtp.host,+        smtpPort = smtp.port,+        smtpUseSsl = smtp.useSsl,+        authType = "password",+        passwordEncrypted = cipher,+        passwordIv = iv,+    )+    EmailDatabase.getInstance(context).emailDao().insertAccount(account)+    EmailSyncWorker.schedulePeriodicSync(context)+    EmailSyncWorker.runOneOffSync(context)+    ImapIdleService.start(context)+    null+}