How to call back send mail in android
To send a callback after sending an email in Android, you can use the sendIntent
and startActivityForResult
methods to launch the email client and then override the onActivityResult
method to receive the result.
Here's an example code snippet:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("message/rfc822");
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Body");
startActivityForResult(sendIntent, REQUEST_SEND_EMAIL);
//...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SEND_EMAIL && resultCode == RESULT_OK) {
// Email sent successfully, send a callback to the activity
Intent callbackIntent = new Intent();
callbackIntent.putExtra("email_sent", true);
sendBroadcast(callbackIntent);
}
}
In this example, we create an Intent
with the ACTION_SEND
action and set the type to message/rfc822
to indicate that we want to send an email. We then add the recipient's email address, subject, and body to the intent using EXTRA_EMAIL
, EXTRA_SUBJECT
, and EXTRA_TEXT
extras.
We then start the email client using startActivityForResult
and pass the REQUEST_SEND_EMAIL
request code.
In the onActivityResult
method, we check if the request code matches the REQUEST_SEND_EMAIL
code and if the result code is RESULT_OK
, which indicates that the email was sent successfully. We then create a new Intent
with a custom extra email_sent
and send a broadcast to the activity using sendBroadcast
.
You can then receive this callback in your activity by overriding the onReceive
method of the BroadcastReceiver
:
public class EmailSentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("email_sent")) {
// Email sent successfully, handle the callback
boolean emailSent = intent.getBooleanExtra("email_sent", false);
//...
}
}
}
Make sure to register the EmailSentReceiver
in your AndroidManifest.xml file:
<receiver android:name=".EmailSentReceiver">
<intent-filter>
<action android:name="email_sent" />
</intent-filter>
</receiver>
This is just one way to send a callback after sending an email in Android. You can customize the approach to fit your specific requirements.