In Android applications, you often need to share data between different apps or send information via e-mail. Android provides several ways to achieve this functionality, making it easy to integrate sharing and e-mail features in your app.
Let's look at how you can implement sharing data between apps and sending e-mails.
Android provides an Intent system that enables apps to share data with other apps. An Intent can be used to pass data like text, images, URLs, etc., between different apps on the device.
The simplest way to share data (like text or URLs) is using an implicit Intent. The system will automatically determine which app can handle the data (such as an email app, messaging app, or social media app).
Here’s how to share a simple piece of text:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "This is the text I want to share.");
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, "Share via"));
Intent.ACTION_SEND: Specifies the action to share data.Intent.EXTRA_TEXT: The key for text data in the intent.setType("text/plain"): Specifies the MIME type for the data being shared.createChooser(): Displays a dialog to let the user select which app to use to share the data.This will open a chooser dialog, where the user can choose an app (such as a messaging or social media app) to share the text.
You can also share files like images, videos, or documents by attaching them to an Intent:
File file = new File(Environment.getExternalStorageDirectory(), "example.jpg");
Uri fileUri = FileProvider.getUriForFile(this, "com.example.app.fileprovider", file);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
shareIntent.setType("image/jpeg"); // Specify the MIME type (e.g., image/jpeg, application/pdf)
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Grant read permission to the receiving app
startActivity(Intent.createChooser(shareIntent, "Share via"));
Intent.EXTRA_STREAM: The key for passing the file URI.FileProvider.getUriForFile(): Used to get a content URI for a file. This ensures secure access to files.Intent.FLAG_GRANT_READ_URI_PERMISSION: Grants the receiving app permission to read the URI.For sharing files, you must define a FileProvider in your app’s AndroidManifest.xml to securely share files using content:// URIs.
Example:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.app.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
And in res/xml/file_paths.xml, define file paths:
<paths>
<external-path name="external_files" path="." />
</paths>
Sending emails from an Android app is commonly done via an Intent to open an email client (such as Gmail, Outlook, etc.) with pre-filled data. You can pre-fill fields like the recipient, subject, and body of the email.
To send an e-mail via an email client, use an Implicit Intent with the ACTION_SENDTO action and the mailto: scheme. This allows you to open the default email app with pre-populated fields.
Here’s how to create an Intent for sending an email:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:")); // Only email apps should handle this intent
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"example@email.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject of the email");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body of the email");
if (emailIntent.resolveActivity(getPackageManager()) != null) {
startActivity(emailIntent); // Open the default email app with the pre-filled details
}
Intent.ACTION_SENDTO: Indicates that this is a "send-to" action (e.g., send an email).mailto:: The URI scheme for sending e-mails.Intent.EXTRA_EMAIL: The recipient’s email address.Intent.EXTRA_SUBJECT: The subject of the email.Intent.EXTRA_TEXT: The body of the email.When the user taps on the Intent, the system will open the default email app with the pre-filled information.
If you need to send an email with attachments, you can add attachments to the Intent.EXTRA_STREAM:
File file = new File(Environment.getExternalStorageDirectory(), "document.pdf");
Uri fileUri = FileProvider.getUriForFile(this, "com.example.app.fileprovider", file);
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"example@email.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject with Attachment");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Here is an email with an attachment.");
emailIntent.putExtra(Intent.EXTRA_STREAM, fileUri); // Attach the file
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Grant permission to access the file
if (emailIntent.resolveActivity(getPackageManager()) != null) {
startActivity(emailIntent);
}
This will attach the file specified by the URI to the email. Just like with sharing files, you'll need to ensure the app has permission to access the file via a FileProvider.
If you need more control or want to send an email without relying on the user's email app, you can use third-party libraries like JavaMail or integrate email services like SendGrid or Amazon SES for sending emails directly from the app (without opening an email client).
To send email without opening an email client, you can use the JavaMail API. This requires adding the JavaMail dependency to your project and configuring an SMTP server.
Example:
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email@gmail.com", "your-password");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email@gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient-email@example.com"));
message.setSubject("Subject");
message.setText("Email Body");
Transport.send(message); // Send the email
Log.d("Email", "Email Sent Successfully");
} catch (MessagingException e) {
e.printStackTrace();
}
Note: Be cautious when using your email password directly in your app. It’s better to use OAuth2 for authentication when connecting to email servers like Gmail.
Android makes it easy to share data and send e-mails through Intents. For simple sharing, you can use ACTION_SEND to share text, files, or URLs with other apps. When sending emails, you can pre-fill the recipient, subject, and body fields, and optionally include attachments, making it easy for users to send e-mails directly from your app.
For more advanced use cases, such as sending e-mails without using the email client or sending bulk e-mails, you can integrate third-party libraries like JavaMail or use services like SendGrid or Amazon SES.
By implementing these features, you allow users to interact with your app in meaningful ways, enhancing their experience and making your app more versatile.
Open this section to load past papers