Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Added PDU generation via android-smsmms and MMS sender/handler

Jake Daynesadfa171d0fdf
diff --git a/android/app/build.gradle b/android/app/build.gradle
index f49acb2b..66eb98c1 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -67,6 +67,7 @@ dependencies {
implementation 'com.google.android.material:material:1.12.0'
implementation 'androidx.constraintlayout:constraintlayout:2.2.1'
implementation 'com.googlecode.libphonenumber:libphonenumber:9.0.4'
+ implementation 'com.klinkerapps:android-smsmms:5.2.6'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.2.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1'
diff --git a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
index 8f1e448c..dca73a5e 100644
--- a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
+++ b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt
@@ -9,6 +9,13 @@ import com.google.firebase.messaging.RemoteMessage
import com.httpsms.SentReceiver.FailedMessageWorker
import timber.log.Timber
+import com.google.android.mms.pdu.CharacterSets
+import com.google.android.mms.pdu.EncodedStringValue
+import com.google.android.mms.pdu.PduBody
+import com.google.android.mms.pdu.PduComposer
+import com.google.android.mms.pdu.PduPart
+import com.google.android.mms.pdu.SendReq
+
class MyFirebaseMessagingService : FirebaseMessagingService() {
// [START receive_message]
override fun onMessageReceived(remoteMessage: RemoteMessage) {
@@ -158,6 +165,11 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
}
Receiver.register(applicationContext)
+
+ if (message.attachments != null && message.attachments.isNotEmpty()) {
+ return handleMmsMessage(message)
+ }
+
val parts = getMessageParts(applicationContext, message)
if (parts.size == 1) {
return handleSingleMessage(message, parts.first())
@@ -165,6 +177,107 @@ class MyFirebaseMessagingService : FirebaseMessagingService() {
return handleMultipartMessage(message, parts)
}
+ private fun handleMmsMessage(message: Message): Result {
+ Timber.d("Processing MMS for message ID [${message.id}]")
+ val apiService = HttpSmsApiService.create(applicationContext)
+
+ val downloadedFiles = mutableListOf<java.io.File>()
+
+ try {
+ for ((index, attachment) in message.attachments!!.withIndex()) {
+ val file = apiService.downloadAttachment(applicationContext, attachment.url, message.id, index)
+ if (file == null) {
+ handleFailed(applicationContext, message.id, "Failed to download attachment or file size exceeded 1.5MB.")
+ return Result.failure()
+ }
+ downloadedFiles.add(file)
+ }
+
+ val sendReq = SendReq()
+
+ val encodedContact = EncodedStringValue(message.contact)
+ sendReq.to = arrayOf(encodedContact)
+
+ val pduBody = PduBody()
+
+ if (message.content.isNotEmpty()) {
+ val textPart = PduPart()
+ textPart.setCharset(CharacterSets.UTF_8)
+ textPart.contentType = "text/plain".toByteArray()
+ textPart.name = "text".toByteArray()
+ textPart.contentId = "text".toByteArray()
+ textPart.contentLocation = "text".toByteArray()
+
+ var messageBody = message.content
+ val encryptionKey = Settings.getEncryptionKey(applicationContext)
+ if (message.encrypted && !encryptionKey.isNullOrEmpty()) {
+ messageBody = Encrypter.decrypt(encryptionKey, messageBody)
+ }
+ textPart.data = messageBody.toByteArray(Charsets.UTF_8)
+
+ pduBody.addPart(textPart)
+ }
+
+ for ((index, file) in downloadedFiles.withIndex()) {
+ val attachment = message.attachments[index]
+ val fileBytes = file.readBytes()
+
+ val mediaPart = PduPart()
+ mediaPart.contentType = attachment.contentType.toByteArray()
+
+ val fileName = "attachment_$index".toByteArray()
+ mediaPart.name = fileName
+ mediaPart.contentId = fileName
+ mediaPart.contentLocation = fileName
+ mediaPart.data = fileBytes
+
+ pduBody.addPart(mediaPart)
+ }
+
+ sendReq.body = pduBody
+
+ val pduComposer = PduComposer(applicationContext, sendReq)
+ val pduBytes = pduComposer.make()
+
+ if (pduBytes == null) {
+ Timber.e("PduComposer failed to generate PDU byte array")
+ handleFailed(applicationContext, message.id, "Failed to compose MMS PDU.")
+ return Result.failure()
+ }
+
+ val mmsDir = java.io.File(applicationContext.cacheDir, "mms_attachments")
+ if (!mmsDir.exists()) {
+ mmsDir.mkdirs()
+ }
+
+ val pduFile = java.io.File(mmsDir, "pdu_${message.id}.dat")
+ java.io.FileOutputStream(pduFile).use { it.write(pduBytes) }
+
+ val pduUri = androidx.core.content.FileProvider.getUriForFile(
+ applicationContext,
+ "${BuildConfig.APPLICATION_ID}.fileprovider",
+ pduFile
+ )
+
+ val sentIntent = createPendingIntent(message.id, SmsManagerService.sentAction())
+ SmsManagerService().sendMultimediaMessage(applicationContext, pduUri, message.sim, sentIntent)
+
+ Timber.d("Successfully dispatched MMS for message ID [${message.id}]")
+ return Result.success()
+
+ } catch (e: Exception) {
+ Timber.e(e, "Failed to send MMS for message ID [${message.id}]")
+ handleFailed(applicationContext, message.id, e.message ?: "Internal error while building or sending MMS.")
+ return Result.failure()
+ } finally {
+ downloadedFiles.forEach { file ->
+ if (file.exists()) {
+ file.delete()
+ }
+ }
+ }
+ }
+
private fun handleMultipartMessage(message:Message, parts: ArrayList<String>): Result {
Timber.d("sending multipart SMS for message with ID [${message.id}]")
return try {
diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
index 3d813e13..4f1fe5dd 100644
--- a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt
@@ -11,6 +11,8 @@ import java.net.URI
import java.net.URL
import java.util.logging.Level
import java.util.logging.Logger.getLogger
+import java.io.File
+import java.io.FileOutputStream
class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
@@ -156,6 +158,51 @@ class HttpSmsApiService(private val apiKey: String, private val baseURL: URI) {
return true
}
+ fun downloadAttachment(context: Context, urlString: String, messageId: String, attachmentIndex: Int): File? {
+ val request = Request.Builder().url(urlString).build()
+
+ try {
+ val response = client.newCall(request).execute()
+ if (!response.isSuccessful) {
+ Timber.e("Failed to download attachment: ${response.code}")
+ response.close()
+ return null
+ }
+
+ val maxSizeBytes = 1.5 * 1024 * 1024 // most (modern?) carriers have a 2MB limit, so targetting 1.5MB should be safe
+ val contentLength = response.body?.contentLength() ?: -1L
+ if (contentLength > maxSizeBytes) {
+ Timber.e("Attachment is too large ($contentLength bytes).")
+ response.close()
+ return null
+ }
+
+ val mmsDir = File(context.cacheDir, "mms_attachments")
+ if (!mmsDir.exists()) {
+ mmsDir.mkdirs()
+ }
+
+ val tempFile = File(mmsDir, "mms_${messageId}_$attachmentIndex")
+ val inputStream = response.body?.byteStream()
+ val outputStream = FileOutputStream(tempFile)
+ inputStream?.copyTo(outputStream)
+
+ outputStream.close()
+ inputStream?.close()
+ response.close()
+
+ if (tempFile.length() > maxSizeBytes) {
+ tempFile.delete()
+ Timber.e("Downloaded file exceeded 1.5MB limit.")
+ return null
+ }
+
+ return tempFile
+ } catch (e: Exception) {
+ Timber.e(e, "Exception while downloading attachment")
+ return null
+ }
+ }
private fun sendEvent(messageId: String, event: String, timestamp: String, reason: String? = null): Boolean {
var reasonString = "null"
diff --git a/android/app/src/main/java/com/httpsms/SentReceiver.kt b/android/app/src/main/java/com/httpsms/SentReceiver.kt
index 7995c35c..00e76c2c 100644
--- a/android/app/src/main/java/com/httpsms/SentReceiver.kt
+++ b/android/app/src/main/java/com/httpsms/SentReceiver.kt
@@ -17,6 +17,8 @@ import timber.log.Timber
internal class SentReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
+ val messageId = intent.getStringExtra(Constants.KEY_MESSAGE_ID)
+ cleanupPduFile(context, messageId)
when (resultCode) {
Activity.RESULT_OK -> handleMessageSent(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID))
SmsManager.RESULT_ERROR_GENERIC_FAILURE -> handleMessageFailed(context, intent.getStringExtra(Constants.KEY_MESSAGE_ID), "GENERIC_FAILURE")
@@ -27,6 +29,26 @@ internal class SentReceiver : BroadcastReceiver() {
}
}
+ private fun cleanupPduFile(context: Context, messageId: String?) {
+ if (messageId == null) return
+
+ try {
+ val baseMessageId = messageId.substringBefore(".")
+ val mmsDir = File(context.cacheDir, "mms_attachments")
+ val pduFile = File(mmsDir, "pdu_$baseMessageId.dat")
+
+ if (pduFile.exists()) {
+ if (pduFile.delete()) {
+ Timber.d("Cleaned up PDU file for message ID [$baseMessageId]")
+ } else {
+ Timber.w("Failed to delete PDU file for message ID [$baseMessageId]")
+ }
+ }
+ } catch (e: Exception) {
+ Timber.e(e, "Error cleaning up PDU file for message ID [$messageId]")
+ }
+ }
+
private fun handleMessageSent(context: Context, messageId: String?) {
if (!Receiver.isValid(context, messageId)) {
return