向电子邮件添加附件:权限被拒绝

时间:2016-12-15 20:56:09

标签: java android email javamail

http://pastie.org/4185959

我已经使用此代码制作了一个邮件应用程序,该应用程序在代码中接受验证参数。单独发送普通邮件工作正常,但添加附件是一个问题,注释行m.addAttachment()使邮件成功发送即使我正确传递文件的路径。这是我使用的代码:

class MailSender extends AsyncTask<Void, Integer, Integer>
    {

        ProgressDialog pd = null;
        /* (non-Javadoc)
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = new ProgressDialog(MailSenderActivity.this);
            pd.setTitle("Uploading...");
            pd.setMessage("Uploading logs. Please wait...");
            pd.setCancelable(false);
            pd.show();

        }

        /* (non-Javadoc)
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Integer doInBackground(Void... params) {


            Mail m = new Mail("from_mail@gmail.com", "password");

            String toAddresses = "to_mail@gmail.com";
            m.setToAddresses(toAddresses);
            m.setFromAddress("from_mail@gmail.com");
            m.setMailSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
            m.setMailBody("Email body.");

            /*try {
                ZipUtility.zipDirectory(new File("/mnt/sdcard/logs/"), new File("/mnt/sdcard/logs.zip"));
            } catch (IOException e1) {
                Log.e("MailApp", "Could not zip folder", e1);
            }*/

            try {
                m.addAttachment("/mnt/sdcard/Pictures/test.jpg");

                if (m.send()) {
                    System.out.println("Message sent");
                    return 1;
                } else {
                    return 2;
                }

            } catch (Exception e) {
                Log.e("MailApp", "Could not send email", e);
            }
            return 3;
        }

        /* (non-Javadoc)
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Integer result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pd.dismiss();

            if(result==1)
                Toast.makeText(MailSenderActivity.this,
                        "Email was sent successfully.", Toast.LENGTH_LONG)
                        .show();
            else if(result==2)
                Toast.makeText(MailSenderActivity.this,
                        "Email was not sent.", Toast.LENGTH_LONG).show();
            else if(result==3)
                Toast.makeText(MailSenderActivity.this,
                        "There was a problem sending the email.",
                        Toast.LENGTH_LONG).show();

        }

Mail.java类

public class Mail extends javax.mail.Authenticator {

    private Multipart attachements;


    private String fromAddress = "";
    private String accountEmail = "";
    private String accountPassword = "";
    private String smtpHost = "smtp.gmail.com";
    private String smtpPort = "465"; // 465,587
    private String toAddresses = "";
    private String mailSubject = "";
    private String mailBody = "";


    public Mail() {
        attachements = new MimeMultipart();

    }

    public Mail(String user, String pass) {
        this();
        accountEmail = user;
        accountPassword = pass;
    }

    public boolean send() throws Exception {

        Properties props = new Properties();
        //props.put("mail.smtp.user", d_email);
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.debug", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", smtpPort);
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        try {
            Session session = Session.getInstance(props, this);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            //fill message
            messageBodyPart.setText(mailBody);
            // add to multipart
            attachements.addBodyPart(messageBodyPart);

            //msg.setText(mailBody);
            msg.setSubject(mailSubject);
            msg.setFrom(new InternetAddress(fromAddress));
            msg.addRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(toAddresses));
            msg.setContent(attachements);

            Transport transport = session.getTransport("smtps");
            transport.connect(smtpHost, 465, accountEmail, accountPassword);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        attachements.addBodyPart(messageBodyPart);
    }

    private String getFormattedDate(Date date)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd-MMM-yyyy hh:mm:ss a");
        return sdf.format(date);
    }

    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(accountEmail, accountPassword);
    }

    /**
     * Gets the fromAddress.
     *
     * @return <tt> the fromAddress.</tt>
     */
    public String getFromAddress() {
        return fromAddress;
    }

    /**
     * Sets the fromAddress.
     *
     * @param fromAddress <tt> the fromAddress to set.</tt>
     */
    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    /**
     * Gets the toAddresses.
     *
     * @return <tt> the toAddresses.</tt>
     */
    public String getToAddresses() {
        return toAddresses;
    }

    /**
     * Sets the toAddresses.
     *
     * @param toAddresses <tt> the toAddresses to set.</tt>
     */
    public void setToAddresses(String toAddresses) {
        this.toAddresses = toAddresses;
    }

    /**
     * Gets the mailSubject.
     *
     * @return <tt> the mailSubject.</tt>
     */
    public String getMailSubject() {
        return mailSubject;
    }

    /**
     * Sets the mailSubject.
     *
     * @param mailSubject <tt> the mailSubject to set.</tt>
     */
    public void setMailSubject(String mailSubject) {
        this.mailSubject = mailSubject;
    }

    /**
     * Gets the mailBody.
     *
     * @return <tt> the mailBody.</tt>
     */
    public String getMailBody() {
        return mailBody;
    }

    /**
     * Sets the mailBody.
     *
     * @param mailBody <tt> the mailBody to set.</tt>
     */
    public void setMailBody(String mailBody) {
        this.mailBody = mailBody;
    }
}

如您所见,addAttachment方法仅接受字符串,特别是文件路径。我已经直接传递了文件路径,因为我有一个名为&#39; test.jpg&#39;在我的图片文件夹中,但我仍然收到此消息:

java.io.FileNotFoundException: /mnt/sdcard/Pictures/test.jpg: open failed: EACCES (Permission denied)

我已经为INTERNET和EXTERNAL_DATA_STORAGE添加了权限,因此不是问题。似乎由于某种原因我无法在图片文件夹中访问此文件。

这里是Amaze中文件的位置:

http://i.imgur.com/nbsWzsb.png

0 个答案:

没有答案