如何使用此代码将音频文件作为附件发送

时间:2012-07-06 04:28:13

标签: android gmail

代码完美无缺。但是它不是作为附件发送的图像文件,而是我想附加一个录制的音频,比如a.3gp作为附件存放在存储卡中。这段代码需要对此进行哪些更改?

Mail.java类是

package com.mycomp.android.test;

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.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;

public class Mail extends javax.mail.Authenticator {

    private Multipart attachements;


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


    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);
    }

    @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;
    }
}

SenderActivity类是:

package com.mycomp.android.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MailSenderActivity extends Activity {

    private static final String GMAIL_EMAIL_ID = "xyz@gmail.com";
    private static final String GMAIL_ACCOUNT_PASSWORD = "xyz";
    private static final String TO_ADDRESSES = "xyz";

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        writeFile();

        final Button send = (Button) this.findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                new MailSenderActivity.MailSender().execute();
            }
        });

    }

    private File imageFile;

    private boolean writeFile() {
        imageFile = new File(
                getApplicationContext().getFilesDir() + "/images/",
                "sample.png");

        String savePath = imageFile.getAbsolutePath();
        System.out.println("savePath :" + savePath + ":");

        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(savePath, false);
        } catch (FileNotFoundException ex) {
            String parentName = new File(savePath).getParent();
            if (parentName != null) {
                File parentDir = new File(parentName);
                if ((!(parentDir.exists())) && (parentDir.mkdirs()))
                    try {
                        fileOutputStream = new FileOutputStream(savePath, false);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

            }
        }

        // here i am using a png from drawable resources as attachment. You can use your own image byteArray while sending mail. 
        Bitmap bitmap = BitmapFactory.decodeResource(
                MailSenderActivity.this.getResources(), R.drawable.english);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] imgBuffer = stream.toByteArray();

        boolean result = true;

        try {
            fileOutputStream.write(imgBuffer);
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result = false;
        } catch (IOException e2) {
            e2.printStackTrace();
            result = false;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    result = false;
                }
            }
        }

        return result;

    }

    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 image. 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(GMAIL_EMAIL_ID, GMAIL_ACCOUNT_PASSWORD);

            String toAddresses = TO_ADDRESSES;
            m.setToAddresses(toAddresses);
            m.setFromAddress(GMAIL_EMAIL_ID);
            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/images"),
//                      new File("/mnt/sdcard/logs.zip"));
//          } catch (IOException e1) {
//              Log.e("MailApp", "Could not zip folder", e1);
//          }

            try {
                String path = imageFile.getAbsolutePath();
                System.out.println("sending path:" + path + ":");
                m.addAttachment(path);

                // m.addAttachment("/mnt/sdcard/logs.zip");

                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();

        }
    }

}

2 个答案:

答案 0 :(得分:0)

sender activity class中,您可以使用类似的内容将音频文件转换为byte array

    try {
        InputStream is = new BufferedInputStream(new FileInputStream("sdcard/bbb.wav"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
   bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();

将其替换为// here i am using a png from drawable resources as attachment. You can use your own image byteArray while sending mail.代码

我没有测试过,但它应该有用。

答案 1 :(得分:0)

您必须将音频文件转换为byte[]格式并通过附件发送:

private byte[] getByteArrayFromAudio(String filePath) throws FileNotFoundException, IOException {
    File file = new File(filePath);
    System.out.println(file.exists() + "!!");

    FileInputStream fis = new FileInputStream(file);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum); 
            System.out.println("read " + readNum + " bytes,");
        }
    } catch (IOException ex) {
        Log.d("error","error");
    }
    byte[] bytes = bos.toByteArray();

    return bytes;
}