2011-05-16 64 views
6

如何在应用程序中将pdf文件从资产附加到电子邮件?我正在使用下面的代码来附加图像,但我不知道如何附上pdf。如何从电子邮件中的资产中附加pdf文件?

EMail.java文件

 
package com.drc.email; 

import android.app.Activity; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class Email extends Activity { 
    Button send,attach; 
    EditText userid,password,from,to,subject,body; 

    private static final int SELECT_PICTURE = 1; 
    private String selectedImagePath=null; 

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

     send = (Button) this.findViewById(R.id.btnsend); 
     attach = (Button) this.findViewById(R.id.btnattach); 
     userid = (EditText) this.findViewById(R.id.userid); 
     password = (EditText) this.findViewById(R.id.password); 
     from = (EditText) this.findViewById(R.id.from); 
     to = (EditText) this.findViewById(R.id.to); 
     subject = (EditText) this.findViewById(R.id.subject); 
     body = (EditText) this.findViewById(R.id.body); 
     attach.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
        // select a file 
       selectedImagePath=null; 
       Intent intent = new Intent(); 
       intent.setType("image/*"); 
       intent.setAction(Intent.ACTION_GET_CONTENT); 
       startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE); 
      } 
     }); 
     send.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View view) { 
       MailSender sender = new MailSender(userid.getText().toString(), password.getText().toString()); 
       try { 
        if(selectedImagePath==null) 
        { 
         sender.sendMail(subject.getText().toString(), body.getText().toString(), from.getText().toString(),to.getText().toString()); 
         Toast.makeText(getBaseContext(), "Send Mail Sucess", Toast.LENGTH_LONG).show(); 
        } 
        else 
        { 
        sender.sendMailAttach(subject.getText().toString(), body.getText().toString(), from.getText().toString(),to.getText().toString(),selectedImagePath.toString(),String.format("image%d.jpeg", System.currentTimeMillis())); 
        Toast.makeText(getBaseContext(), "Send Attach Mail Sucess", Toast.LENGTH_LONG).show(); 
        } 
       } catch (Exception e) { 
        Log.e("SendMail", e.getMessage(), e); 

       } 
       sender=null; 

      } 

     }); 

    } 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == RESULT_OK) { 
      if (requestCode == SELECT_PICTURE) { 
       Uri selectedImageUri = data.getData(); 
       selectedImagePath = getPath(selectedImageUri); 
       //disimage.setImageURI(Uri.parse(selectedImagePath)); 
      } 
     } 
    } 
    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(); 
    // Toast.makeText(this,cursor.getString(column_index).toString(), Toast.LENGTH_LONG); 
     return cursor.getString(column_index); 
    } 
} 

MailSender.java文件

 
package com.drc.email; 

import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
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; 

import java.io.ByteArrayInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Properties; 

public class MailSender extends javax.mail.Authenticator { 

    private String mailhost = "smtp.gmail.com"; 
    private String user; 
    private String password; 
    private Session session; 

    static { 
     // Security.addProvider(new 
     // org.apache.harmony.xnet.provider.jsse.JSSEProvider()); 
    } 

    public MailSender(String user, String password) { 
     this.user = user; 
     this.password = password; 
     System.out.println("Hello"); 
     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) throws Exception { 
     MimeMessage message = new MimeMessage(session); 
     DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); 
     message.setSender(new InternetAddress(sender)); 
     message.setSubject(subject); 
     message.setDataHandler(handler); 
     if (recipients.indexOf(',') > 0) 
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); 
     else 
      message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); 

     Transport.send(message); 
    } 
    public synchronized void sendMailAttach(String subject, String body,String sender, String recipients, String selectedImagePath,String filename) throws Exception { 
     MimeMessage message = new MimeMessage(session); 
     message.setSender(new InternetAddress(sender)); 
     message.setSubject(subject); 
      // Set the email message text. 
      // 
      MimeBodyPart messagePart = new MimeBodyPart(); 
      messagePart.setText(body); 
      // 
      // Set the email attachment file 
      // 
      MimeBodyPart attachmentPart = new MimeBodyPart(); 
      FileDataSource fileDataSource = new FileDataSource(selectedImagePath) { 
       @Override 
       public String getContentType() { 
       return "application/octet-stream"; 
       } 
      }; 
      attachmentPart.setDataHandler(new DataHandler(fileDataSource)); 
      attachmentPart.setFileName(filename); 

      Multipart multipart = new MimeMultipart(); 
      multipart.addBodyPart(messagePart); 
      multipart.addBodyPart(attachmentPart); 

      message.setContent(multipart); 

     if (recipients.indexOf(',') > 0) 
      {message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));} 
     else 
      {message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));} 

     Transport.send(message); 
    } 
    public class ByteArrayDataSource implements DataSource { 
     private byte[] data; 
     private String type; 

     public ByteArrayDataSource(byte[] data, String type) { 
      super(); 
      this.data = data; 
      this.type = type; 
     } 

     public ByteArrayDataSource(byte[] data) { 
      super(); 
      this.data = data; 
     } 

     public void setType(String type) { 
      this.type = type; 
     } 

     public String getContentType() { 
      if (type == null) 
       return "application/octet-stream"; 
      else 
       return type; 
     } 

     public InputStream getInputStream() throws IOException { 
      return new ByteArrayInputStream(data); 
     } 

     public String getName() { 
      return "ByteArrayDataSource"; 
     } 

     public OutputStream getOutputStream() throws IOException { 
      throw new IOException("Not Supported"); 
     } 
    } 
} 

我使用3个外部jar文件。

  1. 的activation.jar
  2. additional.jar
  3. 的mail.jar

回答

0

你应该使用URI等引用到PDF文件myfile.pdf资产目录:

Uri uri=Uri.parse("file:///android_asset/myfile.pdf"); 
+0

嗨巴尔马利,我尝试这个,但这是行不通的,下面的错误来了,安德尔oid.content.ActivityNotFoundException:找不到处理意图的活动{dat = file:///assets/android.pdf} – 2011-05-17 05:38:19

+0

这意味着您没有与PDF文件关联的活动,仅此而已。您需要安装/具有可处理PDF文件的应用程序 – barmaley 2011-05-17 18:16:34

+0

不,我在资产文件夹中有一些pdf文件,但我不知道如何在附加按钮的单击事件上附加pdf文件。 – 2011-05-18 06:13:31

0
i've done for send any file from SD card with mail attachment.. 

Intent sendEmail= new Intent(Intent.ACTION_SEND); 
     sendEmail.setType("rar/image"); 
     sendEmail.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new   
     File("/mnt/sdcard/download/abc.rar"))); 
     startActivity(Intent.createChooser(sendEmail, "Email:")); 
相关问题