0

所以我想用我的应用程序做的是:

我想将反馈发送到带有附件的特定电子邮件地址。但是当我尝试单击发送按钮时,邮件已发送,但邮件中没有附加文件,并且它抛出“打开失败:ENOENT(没有这样的文件或目录)”错误。

我想将所选文件的完整路径(我正在使用aFileChooser)提供给字符串“path”,以便它可以读取文件名并将其附加到邮件中。

最后我想用邮件附加任何图像文件。

指导我的队友。

这是我的 Gmail.java 文件

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
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.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



public class GMail {


    final String emailPort = "587";
    final String smtpAuth = "true";
    final String starttls = "true";
    final String emailHost = "smtp.gmail.com";

    String fromEmail;
    String fromPassword;
    List<String> toEmailList;
    String emailSubject;
    String emailBody;

    Properties emailProperties;
    Session mailSession;
    MimeMessage emailMessage;





    public GMail(String fromEmail, String fromPassword,
                 List<String> toEmailList, String emailSubject, String emailBody) {
        this.fromEmail = fromEmail;
        this.fromPassword = fromPassword;
        this.toEmailList = toEmailList;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;

        emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", emailPort);
        emailProperties.put("mail.smtp.auth", smtpAuth);
        emailProperties.put("mail.smtp.starttls.enable", starttls);
        Log.i("GMail", "Mail server properties set.");
    }

    public MimeMessage createEmailMessage() throws AddressException,
            MessagingException, UnsupportedEncodingException, URISyntaxException {

        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
        for (String toEmail : toEmailList) {
            Log.i("GMail","toEmail: "+toEmail);
            emailMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(toEmail));
        }
        emailMessage.setSubject(emailSubject);
        emailMessage.setContent(emailBody, "text/html");// for a html email
        // emailMessage.setText(emailBody);// for a text email

        //String path="storage/emulated/0/Pictures/Ghost335.jpeg";

        String path ;
        path = toString();
        Multipart _multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(path);

        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(path);

        _multipart.addBodyPart(messageBodyPart);
        emailMessage.setContent(_multipart);


        Log.i("GMail", "Email Message created.");
        return emailMessage;
    }

    public void sendEmail() throws AddressException, MessagingException {

        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromEmail, fromPassword);
        Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients());
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        Log.i("GMail", "Email sent successfully.");
    }

}

这是FeedbackActivity.java文件

import java.io.File;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ipaulpro.afilechooser.utils.FileUtils;

public class FeedbackActivity extends AppCompatActivity {

    private static final String TAG = null;
    private Button sendEmail;
    private Button chooseFileButton;
    private String filename;
    private String username;
    private String password;
    private String pathname;
    public static final int REQUEST_CHOOSER = 1234;
    private static final int FILE_SELECT_CODE = 0;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    // Get the Uri of the selected file
                    Uri uri = data.getData();
                    Log.d(TAG, "File Uri: " + uri.toString());
                    // Get the path
                    String path = FileUtils.getPath(this, uri);
                    Log.d(TAG, "File Path: " + path);
                    // Get the file instance
                    //File file = new File(path);
                    // Initiate the upload

                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(
                    Intent.createChooser(intent, "Select a File to Upload"),
                    FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "Please install a File Manager.",
                    Toast.LENGTH_SHORT).show();
        }
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        final Button send = (Button) this.findViewById(R.id.button);
        send.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Log.i("FeedbackActivity", "Send Button Clicked.");

                String fromEmail = ((TextView) findViewById(R.id.editTextUserEmail))
                        .getText().toString();
                String fromPassword = ((TextView) findViewById(R.id.editTextPassword))
                        .getText().toString();
                final String toEmails ="devemail@gmail.com";
                List<String> toEmailList = Arrays.asList(toEmails
                        .split("\\s*,\\s*"));
                Log.i("FeedbackActivity", "To List: " + toEmailList);
                String emailSubject = ((TextView) findViewById(R.id.editTextSubject))
                        .getText().toString();
                String emailBody = ((TextView) findViewById(R.id.editTextMessage))
                        .getText().toString();

                new SendMailTask(FeedbackActivity.this).execute(fromEmail,
                        fromPassword, toEmailList, emailSubject, emailBody );


            }
        });



        chooseFileButton = (Button) findViewById(R.id.button2);
        chooseFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Create the ACTION_GET_CONTENT Intent

                        showFileChooser();
            }
        });
    }
}

SendMailTask​​.java 文件

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.example.mehul.takeshot.GMail;

public class SendMailTask extends AsyncTask {

    private ProgressDialog statusDialog;
    private Activity FeedbackActivity;

    public SendMailTask(Activity activity) {
        FeedbackActivity = activity;

    }

    protected void onPreExecute() {
        statusDialog = new ProgressDialog(FeedbackActivity);
        statusDialog.setMessage("Getting ready...");
        statusDialog.setIndeterminate(false);
        statusDialog.setCancelable(false);
        statusDialog.show();
    }

    @Override
    protected Object doInBackground(Object... args) {
        try {
            Log.i("SendMailTask", "About to instantiate GMail...");
            publishProgress("Processing input....");
            GMail androidEmail = new GMail(args[0].toString(),
                    args[1].toString(), (List) args[2], args[3].toString(),
                    args[4].toString());
            publishProgress("Preparing mail message....");
            androidEmail.createEmailMessage();
            publishProgress("Sending email....");
            androidEmail.sendEmail();
            publishProgress("Email Sent.");
            Log.i("SendMailTask", "Mail Sent.");
        } catch (Exception e) {
            publishProgress(e.getMessage());
            Log.e("SendMailTask", e.getMessage(), e);
        }
        return null;
    }

    @Override
    public void onProgressUpdate(Object... values) {
        statusDialog.setMessage(values[0].toString());

    }

    @Override
    public void onPostExecute(Object result) {
        statusDialog.dismiss();
    }

}

这是 activity_feedback.xml 文件

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FeedbackActivity"
    android:id="@+id/activity_feedback">

    <TextView
        android:text="User Email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextUserEmail" />

    <TextView
        android:text="User Password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextPassword" />

    <TextView
        android:text="Subject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextSubject" />
    <TextView
        android:text="Message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:lines="4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextMessage" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="Send"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="choose"/>



</LinearLayout>
4

1 回答 1

0

最简单的方法是

    String filename="contacts_sid.vcf"; 
    File filelocation = new   File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
    Uri path = Uri.fromFile(filelocation); 
    Intent emailIntent = new Intent(Intent.ACTION_SEND);

    // set the type to 'email'
    emailIntent .setType("vnd.android.cursor.dir/email");
    String to[] = {"asd@gmail.com"};
    emailIntent .putExtra(Intent.EXTRA_EMAIL, to);

    // the attachment
    emailIntent .putExtra(Intent.EXTRA_STREAM, path);

    // the mail subject
    emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
    startActivity(Intent.createChooser(emailIntent , "Send email..."));

确保您也拥有这些权限

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2017-02-16T06:58:53.007 回答