Metalik
Metalik

Reputation: 943

Can't send image attachment by email intent

I have tried to send image by attachment in email intent. I select gmail app, it seems file is attached, but when i click on send on gmail app it says:

Unfortunately, Gmail has stopped.

Please help me what is the problem and how can i fix it?

AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

MyActivity.java:

public class MyActivity extends Activity {

private static final int SELECT_PICTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 2;
private String selectedImagePath;
TextView uritv=null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    uritv = (TextView) findViewById(R.id.uritxt);

    Button send = (Button) findViewById(R.id.sendBtn);
    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (uritv.getText().toString().equals("URI")) {
                Toast.makeText(getApplicationContext(),"Please choose an image first!",Toast.LENGTH_SHORT).show();
            } else {
                Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                emailIntent.setType("image/*");
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Test Subject");
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "From My App");
                emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(uritv.getText().toString()));
                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
            }
        }
    });

    Button galbtn = (Button) findViewById(R.id.galBtn);
    galbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,
                    "Select Picture"), SELECT_PICTURE);
        }
    });

    Button cambtn = (Button) findViewById(R.id.camBtn);
    cambtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    });

}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            uritv.setText(selectedImagePath.toString());
        }
    }
}
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();
    return cursor.getString(column_index);
}
}

Upvotes: 0

Views: 1786

Answers (3)

Anand Asir
Anand Asir

Reputation: 309

I done some alteration and i can send the Mail successfully.. Since you are using Gmail use a GmailSender Class. Like this

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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 android.net.Uri;

public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
String ContentType = "";
static {
    Security.addProvider(new JSSEProvider());
}

public GMailSender(String user, String password) {
    this.user = user;
    this.password = password;

    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, List<Uri> uriList)
        throws Exception {

    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(user));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                recipients));
        message.setSubject(subject);

        // 3) create MimeBodyPart object and set your message content
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText(body);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart1);

        for (int i = 0; i < uriList.size(); i++) {
            // 4) create new MimeBodyPart object and set DataHandler object
            // to this object
            MimeBodyPart messageBodyPart2 = new MimeBodyPart();
            String filename = uriList
                    .get(i)
                    .getPath()
                    .substring(
                            uriList.get(i).getPath().lastIndexOf("/") + 1,
                            uriList.get(i).getPath().length());// change
                                                                // accordingly
            System.out.println("filename " + filename);
            DataSource source = new FileDataSource(uriList.get(i).getPath());
            messageBodyPart2.setDataHandler(new DataHandler(source));
            messageBodyPart2.setFileName(filename);
            // 5) create Multipart object and add MimeBodyPart objects to
            // this object
            multipart.addBodyPart(messageBodyPart2);
        }

        // 6) set the multiplart object to the message object
        message.setContent(multipart);

        // 7) send message
        Transport.send(message);

        System.out.println("message sent....");
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
}

}

And it is always best to keep your mail sending in a Async Task or Thread. And call this in your send Button.

class SaveAsyncTask extends AsyncTask<Void, Integer, Boolean> {

    private ProgressDialog progressDialogue;
    private Boolean status = false;

    @Override
    protected Boolean doInBackground(Void... arg0) {
        try {
            ArrayList<Uri> uList = new ArrayList<Uri>();
                    u.add(Uri.parse(uritv.getText().toString()));           
            try {
                GMailSender sender = new GMailSender("<Sender Mail>",
                        "<Sender Password>");
                Log.d("TAG: ", "Mail SENT"); 
                sender.sendMail("Subject Text", "Body Text", "<Sender Mail>", "<Recipient Mail>", uList);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return status;
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }

    }

    protected void onPreExecute() {
        progressDialogue = ProgressDialog.show(MainActivity.this,
                "Sending Mail...",
                "Please Wait..", true,
                false);
    }

    protected void onProgressUpdate(Integer... progress) {

    }

    protected void onPostExecute(Boolean result) {
        // result is the value returned from doInBackground
        progressDialogue.dismiss();
    }

}

Upvotes: 0

Dinesh Prajapati
Dinesh Prajapati

Reputation: 9510

yes the problem is with the URI you build to get the file path. you are taking the raw file path which is not the case with the URI. it should be like below

content://media/external/images/media

Please check your path and test that again

Upvotes: 1

RajaReddy PolamReddy
RajaReddy PolamReddy

Reputation: 22493

It requires Internet permissions, add this permission in manifest file

<uses-permission android:name="android.permission.INTERNET"/>

Upvotes: 1

Related Questions