如何在电子邮件中附加来自资产的PDF文件?

19

我该如何在我的应用程序中将assets中的pdf文件附加到电子邮件中?我正在使用以下代码附加图像,但我不知道如何附加pdf。

EMail.java文件

包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;
/** 当活动第一次创建时调用。 */ @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) { // 选择一个文件 selectedImagePath=null; Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"选择图片"), 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(), "邮件发送成功", 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(), "附带文件的邮件发送成功", 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); } } } 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(); 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 {
// 邮箱服务器地址,这里使用 Gmail 的地址。 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"); // SMTP 认证,需要验证用户身份 props.put("mail.smtp.port", "465"); // 邮箱服务器端口号 props.put("mail.smtp.socketFactory.port", "465"); // SSL 加密的 Socket 端口号 props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); // SSL 加密的 Socket 类 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); // 设置邮件主题 // 设置邮件内容 MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(body); // 设置附件 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)); // 如果收件人有多个,分

我正在使用3个外部jar文件。

  1. activation.jar
  2. additional.jar
  3. mail.jar
2个回答

3
您应该使用类似于URI的方式,在资产目录中引用名为myfile.pdf的PDF文件:
Uri uri=Uri.parse("file:///android_asset/myfile.pdf"); 

嗨barmaley,我尝试了这个但是它不起作用,出现以下错误:android.content.ActivityNotFoundException: No Activity found to handle Intent { dat=file:///assets/android.pdf }。 - Dipak Keshariya
这意味着您没有与PDF文件相关联的活动,仅此而已。您需要安装/拥有能够处理PDF文件的应用程序。 - Barmaley
不,我有一些PDF文件在资产文件夹中,但我不知道如何在单击附加按钮的事件上附加PDF文件。 - Dipak Keshariya
看起来它正在工作,但当你发送邮件时,附件就不见了... - Roel
2
看起来你需要先将文件复制到外部目录(例如sdcard) - Simon Rolin
1
当你的目标是Nougat及以上版本(25+)时,这将不再起作用,你需要使用存储访问框架。https://developer.android.com/about/versions/nougat/android-7.0-changes.html#sharing-files https://developer.android.com/training/secure-file-sharing/index.html - Tim Kist

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:"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接