public class SmsReceiver extends BroadcastReceiver {
code
private static final String TAG = "SmsReceiver";
private static final String DESIRED_NUMBER = "+79117629915"; // Replace with your desired sender number
// private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public static final String SMS_MESSAGE_RECEIVED_ACTION = "SMS_MESSAGE_RECEIVED_ACTION";
public static final String SMS_MESSAGE_BODY = "SMS_MESSAGE_BODY";
code
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String sender = smsMessage.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
if (DESIRED_NUMBER.equals(sender)) {
Log.d(TAG, "Received SMS from " + sender + ": " + messageBody);
Toast.makeText(context, "SMS from desired sender: " + messageBody, Toast.LENGTH_SHORT).show();
// Optionally, start the EmailService to send this message via email
// Intent emailIntent = new Intent(context, EmailService.class);
// emailIntent.putExtra("message_body", messageBody);
// Send a local broadcast
Intent localIntent = new Intent(SMS_MESSAGE_RECEIVED_ACTION);
localIntent.putExtra(SMS_MESSAGE_BODY, messageBody);
LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
}
}
}
}
}
}
An email service should run async and not in main thread.
To ensure that email sending operations are performed asynchronously and not on the main thread, you can use services like IntentService or define your own Service that performs the operations in a separate thread. Below, I'll provide a sample implementation of an EmailService that extends IntentService to handle email sending in the background.
EmailService Implementation
First, you need to add the EmailService class that runs in the background and handles the email sending logic.
java
package com.example.smstoemailforwarder;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailService extends IntentService {
private static final String TAG = "EmailService";
public EmailService() {
super("EmailService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String messageBody = intent.getStringExtra("message_body");
// Replace these with your actual email details
String recipientEmail = "recipient@example.com";
String senderEmail = "sender@example.com";
String senderPassword = "senderpassword"; // It's recommended to not store passwords directly in the code
sendEmail(senderEmail, senderPassword, recipientEmail, "SMS Forward", messageBody);
}
}
private void sendEmail(String from, String password, String to, String subject, String body) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.your-email-provider.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
Log.d(TAG, "Email sent successfully");
} catch (MessagingException e) {
Log.e(TAG, "Failed to send email", e);
}
}
}
Using the EmailService in SmsReceiver
In your SmsReceiver class, you will uncomment the parts that start the EmailService and ensure that these lines are executed when the SMS from the desired sender is received.
java
package com.example.smstoemailforwarder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class SmsReceiver extends BroadcastReceiver {
private static final String TAG = "SmsReceiver";
private static final String DESIRED_NUMBER = "+79117629915"; // Replace with your desired sender number
public static final String SMS_MESSAGE_RECEIVED_ACTION = "SMS_MESSAGE_RECEIVED_ACTION";
public static final String SMS_MESSAGE_BODY = "SMS_MESSAGE_BODY";
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
String sender = smsMessage.getDisplayOriginatingAddress();
String messageBody = smsMessage.getMessageBody();
if (DESIRED_NUMBER.equals(sender)) {
Log.d(TAG, "Received SMS from " + sender + ": " + messageBody);
Toast.makeText(context, "SMS from desired sender: " + messageBody, Toast.LENGTH_SHORT).show();
// Start the EmailService to send this message via email
Intent emailIntent = new Intent(context, EmailService.class);
emailIntent.putExtra("message_body", messageBody);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(emailIntent);
} else {
context.startService(emailIntent);
}
// Send a local broadcast
Intent localIntent = new Intent(SMS_MESSAGE_RECEIVED_ACTION);
localIntent.putExtra(SMS_MESSAGE_BODY, messageBody);
LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
}
}
}
}
}
}
Notes
Permissions: Ensure that you have the necessary permissions defined in your AndroidManifest.xml for receiving SMS and accessing the internet:
Security Considerations: Avoid hardcoding sensitive information like email passwords directly in the source code. Consider using more secure methods for handling sensitive data, such as encrypted storage or environment variables.
Testing
To test the setup:
Deploy the application on a compatible device/emulator.
Send an SMS to the device from the specified number.
Check the logs or toast messages to confirm if the SMS is received and processed.
Verify if the email was sent successfully by checking your email client.