Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4626748
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T03:27:57+00:00 2026-05-22T03:27:57+00:00

How do I attach pdf file from assets to email in my application? I

  • 0

How do I attach pdf file from assets to email in my application? I am using following code to attach image but I don’t know how to attach pdf.

EMail.java file

package com.drc.email;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Email extends Activity {
    Button send,attach;
    EditText userid,password,from,to,subject,body;

    private static final int SELECT_PICTURE = 1;
    private String selectedImagePath=null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        send = (Button) this.findViewById(R.id.btnsend);
        attach = (Button) this.findViewById(R.id.btnattach);
        userid = (EditText) this.findViewById(R.id.userid);
        password = (EditText) this.findViewById(R.id.password);
        from = (EditText) this.findViewById(R.id.from);
        to = (EditText) this.findViewById(R.id.to);
        subject = (EditText) this.findViewById(R.id.subject);
        body = (EditText) this.findViewById(R.id.body);
        attach.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                  // select a file
                selectedImagePath=null;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
            }
        });
        send.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                MailSender sender = new MailSender(userid.getText().toString(), password.getText().toString());
                try {
                    if(selectedImagePath==null)
                    {
                         sender.sendMail(subject.getText().toString(), body.getText().toString(), from.getText().toString(),to.getText().toString());
                         Toast.makeText(getBaseContext(), "Send Mail Sucess", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                     sender.sendMailAttach(subject.getText().toString(), body.getText().toString(), from.getText().toString(),to.getText().toString(),selectedImagePath.toString(),String.format("image%d.jpeg", System.currentTimeMillis()));
                     Toast.makeText(getBaseContext(),  "Send Attach Mail Sucess", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Log.e("SendMail", e.getMessage(), e);

                }
                sender=null;

            }

        });

    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                //disimage.setImageURI(Uri.parse(selectedImagePath));
            }
        }
    }
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
     //   Toast.makeText(this,cursor.getString(column_index).toString(), Toast.LENGTH_LONG);
        return cursor.getString(column_index);
    }
}

MailSender.java file

package com.drc.email;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class MailSender extends javax.mail.Authenticator {

    private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;

    static {
        // Security.addProvider(new
        // org.apache.harmony.xnet.provider.jsse.JSSEProvider());
    }

    public MailSender(String user, String password) {
        this.user = user;
        this.password = password;
        System.out.println("Hello");
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body,String sender, String recipients) throws Exception {
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        message.setDataHandler(handler);
        if (recipients.indexOf(',') > 0)
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));

        Transport.send(message);
    }
    public synchronized void sendMailAttach(String subject, String body,String sender, String recipients, String selectedImagePath,String filename) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
            // Set the email message text.
            //
            MimeBodyPart messagePart = new MimeBodyPart();
            messagePart.setText(body);
            //
            // Set the email attachment file
            //
            MimeBodyPart attachmentPart = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(selectedImagePath) {
                @Override
                public String getContentType() {
                return "application/octet-stream";
                }
            };
            attachmentPart.setDataHandler(new DataHandler(fileDataSource));
            attachmentPart.setFileName(filename);

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messagePart);
            multipart.addBodyPart(attachmentPart);

            message.setContent(multipart);

        if (recipients.indexOf(',') > 0)
            {message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));}
        else
            {message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));}

        Transport.send(message);
    }
    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
}

I am using 3 external jar files.

  1. activation.jar
  2. additional.jar
  3. mail.jar
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T03:27:58+00:00Added an answer on May 22, 2026 at 3:27 am

    You should be referencing to PDF file myfile.pdf in asset directory using URI like:

    Uri uri=Uri.parse("file:///android_asset/myfile.pdf"); 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to attach a PDF attachment to an email being sent with System.Net.Mail.
I need to attach a file with mailx but at the moment I am
I'd like to attach a PDF file stored as binary object in SQL Server
I've got a project where I'm using a PDF generator to send a file
I have a method that returns a PDF file using DOMPDF . It sends
I am using PHP's mail function to send an email, but I am going
I need to convert some files to PDF and then attach them to an
Im sending mails from a web application running on a glassfish server, which was
How do I attach a file with a very unfriendly name (like a file
I have written an apex class that will create a PDF quote and attach

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.