ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development
    EC-333
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    EC-333›Sending E-mail
    Mobile Application DevelopmentTopic 21 of 33

    Sending E-mail

    6 minread
    1,083words
    Intermediatelevel

    Sharing Data and Sending E-mail in Android

    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.


    1. Sharing Data Between Apps

    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.

    A. Sharing Text, URLs, and Files via Intent

    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.

    B. Sharing Files (Images, Documents, etc.)

    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>
    

    2. Sending E-mail in Android

    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.

    A. Sending an E-mail Using an Intent

    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.

    B. Adding Attachments to the E-mail

    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.


    3. Handling Email with Third-Party Libraries

    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).

    A. Using JavaMail

    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.


    4. Conclusion

    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.

    Previous topic 20
    Getting Feedback
    Next topic 22
    Displaying Maps

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,083
      Code examples0
      DifficultyIntermediate