Не могу отправить почту с вложением в Android

У меня проблема с отправкой почты с вложением. Я использую библиотеки Javamail (mail.jar, activitation.jar и Additional.jar). Я могу отправить почту точно. Но я не могу отправить почту с вложением изображения на почту. Я выбираю изображение из галереи, и оно добавляется как мое имя файла

 File f = new File("file://" + uri.getPath());

Я думаю, что у меня есть проблема, когда источник данных взял путь моего файла. Все, что вы можете видеть в моем коде, гораздо больше:(я решил эту проблему, и это последняя ситуация в моем коде)

Прежде всего, я добавлю к просмотру моего вложения:

Button Add = (Button) findViewById(R.id.btnAdd);

    Add.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View view) {
            onAddAttachment2("image/*");

        }
    });

вот мой код onAddAttachment2 и onActivityResult

 private void onAddAttachment2(final String mime_type) {



            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(mime_type);
            startActivityForResult(Intent.createChooser(i, null),
                    ACTIVITY_REQUEST_PICK_ATTACHMENT);
        }

    protected void onActivityResult(int requestCode, int resultCode,
        Intent imageReturnedIntent) {

    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    mAttachments = (LinearLayout) findViewById(R.id.attachments);

    switch (requestCode) {
    case ACTIVITY_REQUEST_PICK_ATTACHMENT:

        Uri _uri = imageReturnedIntent.getData();

        addAttachment(_uri);

        Cursor cursor = getContentResolver()
                .query(_uri,
                        new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
                        null, null, null);
        cursor.moveToFirst();
        String imageFilePath = cursor.getString(0);

            uris.add(imageFilePath);



        Log.v("imageFilePath", imageFilePath);
        break;
    }
}

Как вы видите, у меня есть метод AddAttachment. Вот код:

private void addAttachment(Uri uri) {
        addAttachment(uri, null);
    }

    private void addAttachment(Uri uri, String contentType) {
        long size = -1;
        String name = null;

        ContentResolver contentResolver = getContentResolver();

        Cursor metadataCursor = contentResolver.query(uri, new String[] {
                OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }, null,
                null, null);

        if (metadataCursor != null) {
            try {
                if (metadataCursor.moveToFirst()) {
                    name = metadataCursor.getString(0);
                    size = metadataCursor.getInt(1);
                }
            } finally {
                metadataCursor.close();
            }
        }

        if (name == null) {
            name = uri.getLastPathSegment();
        }

        String usableContentType = contentType;
        if ((usableContentType == null)
                || (usableContentType.indexOf('*') != -1)) {
            usableContentType = contentResolver.getType(uri);
        }
        if (usableContentType == null) {
            usableContentType = getMimeTypeByExtension(name);
        }

        if (size <= 0) {
            String uriString = uri.toString();
            if (uriString.startsWith("file://")) {
                Log.v(LOG_TAG, uriString.substring("file://".length()));
                File f = new File(uriString.substring("file://".length()));
                size = f.length();
            } else {
                Log.v(LOG_TAG, "Not a file: " + uriString);
            }
        } else {
            Log.v(LOG_TAG, "old attachment.size: " + size);
        }
        Log.v(LOG_TAG, "new attachment.size: " + size);

        Attachment attachment = new Attachment();
        attachment.uri = uri;
        attachment.contentType = usableContentType;
        attachment.name = name;
        attachment.size = size;

        View view = getLayoutInflater().inflate(
                R.layout.message_compose_attachment, mAttachments, false);
        TextView nameView = (TextView) view.findViewById(R.id.attachment_name);
        ImageButton delete = (ImageButton) view
                .findViewById(R.id.attachment_delete);
        nameView.setText(attachment.name);
        delete.setTag(view);
        view.setTag(attachment);
        mAttachments.addView(view);


        delete.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View view) {

                uris.remove(view.getTag());
                mAttachments.removeView((View) view.getTag());


            }
        });
    }

и класс Attachment, который имеет свойства

static class Attachment implements Serializable {
        private static final long serialVersionUID = 3642382876618963734L;
        public String name;
        public String contentType;
        public long size;
        public Uri uri;
    }

наконец, в моем классе Mail.java у меня есть метод AddAttachment:

public void addAttachment(String file) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();

        FileDataSource source =  new FileDataSource(file);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(file);

    _multipart.addBodyPart(messageBodyPart);
}

Когда я нажал кнопку "Отправить", она была отправлена ​​на адрес. Но моя привязанность не может быть показана. У меня нет ошибок при отправке почты. Я надеюсь, что у вас было решение этой проблемы...

Изменить: ОК, наконец, я решил проблему!.. Сначала я определил ArrayList<String> uris = new ArrayList<String>();

Затем я использовал его в моем методе onActivityResult, как это uris.add(imageFilePath);

наконец, до m.send Блок кода я добавил изображения:

for (int i = 0; i<uris.size(); i++)
                    {
                    m.addAttachment(uris.get(i).toString());
                    }

в моем классе Mail.java изменения показываются так:

public void addAttachment(String file) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();

            FileDataSource source =  new FileDataSource(file);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(file);

        _multipart.addBodyPart(messageBodyPart);
    }

2 ответа

Там определенно проблема MIME Type. Если вы хотите, чтобы изображение было прикреплено к электронной почте, вы можете отправить его, просто используя

private void sendEmail(String[] to,String[] cc,String subject, String message)
    {

        ArrayList<Uri> uris = new ArrayList<Uri>();


        Uri u = Uri.fromFile(new File(front_image));
        Uri u1 = Uri.fromFile(new File(side_image));
        uris.add(u);
        uris.add(u1);



        Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        emailIntent.setType("image/jpg");
        emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
        emailIntent.putExtra(Intent.EXTRA_CC, cc);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        emailIntent.putExtra(Intent.EXTRA_TEXT, message);
        emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        /*emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_right_latest_path));
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_right_prev_path));
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_front_latest_path));
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + show_front_prev_path));*/
        startActivity(Intent.createChooser(emailIntent, "Email"));


    }  

Я надеюсь, что строка, которую вы передаете методу addAttachment, является именем файла, а не URL-адресом (т. Е. Не начинается с "file:").

Чтобы устранить проблему, добавьте код в метод addAttachment, который использует FileInputStream, и посмотрите, сможете ли вы прочитать данные в файле. Если вы не можете, JavaMail тоже не сможет.

Кроме того, включите отладку сеанса и изучите трассировку протокола, чтобы увидеть, что на самом деле отправляет JavaMail. Это может дать больше подсказок. Или в коде, который фактически отправляет сообщение, добавьте msg.writeTo(новый FileOutputStream("msg.txt")) и посмотрите, что записано в файл.

Другие вопросы по тегам